Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indentation and new line command for XMLwriter in C#

Tags:

c#

xml

xmlwriter

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(); 
like image 275
Dark Knight Avatar asked Nov 04 '10 05:11

Dark Knight


1 Answers

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 } 
like image 59
Dennis Avatar answered Sep 21 '22 05:09

Dennis