Indentation and new line command for XMLwriter in C#

Dark Knight picture Dark Knight · Nov 4, 2010 · Viewed 45.4k times · Source

I am writing some data to XML file...but when I open it all the values are in a single line...how can write it in readable format?ie each node in new line and indentation?

FileStream fs = new FileStream("myfile.xml", FileMode.Create);

XmlWriter w = XmlWriter.Create(fs);

w.WriteStartDocument();
w.WriteStartElement("myfile");                 

w.WriteElementString("id", id.Text);
w.WriteElementString("date", dateTimePicker1.Text);
w.WriteElementString("version", ver.Text);
w.WriteEndElement();
w.WriteEndDocument();
w.Flush();
fs.Close();

Answer

Dennis picture Dennis · Nov 4, 2010

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
}