Indentation and new line command for XMLwriter in C# Indentation and new line command for XMLwriter in C# xml xml

Indentation and new line command for XMLwriter in C#


Use a XmlTextWriter instead of XmlWriter and then set the Indentation properties.

Example

string filename = "MyFile.xml";using (FileStream fileStream = new FileStream(filename, FileMode.Create))using (StreamWriter sw = new StreamWriter(fileStream))using (XmlTextWriter xmlWriter = new XmlTextWriter(sw)){  xmlWriter.Formatting = Formatting.Indented;  xmlWriter.Indentation = 4;  // ... Write elements}

Following @jumbo comment, this could also be implemented like in .NET 2.

var filename = "MyFile.xml";var settings = new XmlWriterSettings() {    Indent = true,    IndentChars = "    "}using (var w = XmlWriter.Create(filename, settings)){    // ... Write elements}


You need to first create an XmlWriterSettings object that specifies your indentation, then when creating your XmlWriter, pass in the XmlWriterSettings after your path.

Additionally, I use the using block to let C# handle the disposing of my resources so that I don't need to worry about losing any resources on an exception.

{  XmlWriterSettings xmlWriterSettings = new XmlWriterSettings()  {    Indent = true,    IndentChars = "\t",    NewLineOnAttributes = true  };  using (XmlWriter w= XmlWriter.Create("myfile.xml", xmlWriterSettings))  {    w.WriteStartDocument();    w.WriteStartElement("myfile");    w.WriteElementString("id", id.Text);    w.WriteElementString("date", dateTimePicker1.Text);    w.WriteElementString("version", ver.Text);    w.WriteEndElement();    w.WriteEndDocument();  }}


Check the Settings property:

w.Settings.Indent = true;

Edit: You can't set it directly:

System.Xml.XmlWriter.Create("path", new System.Xml.XmlWriterSettings())