Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize an XmlDocument to a well-formatted human-readable XML?

Tags:

c#

.net

xml

I use an XmlDocument.WriteTo(XmlWriter) method to serialize an XmlDocument to a text file. I have also tried XmlDocument.OuterXml. Both output a single-line XML text which is very hard (up to impossible in case of a reasonably big XML document) to read for a human.

Is there a way to output a well-formatted human-readable XML text instead? I mean with every element starting at a new line and indentation used to visualize hierarchy levels.

like image 677
Ivan Avatar asked Sep 20 '25 11:09

Ivan


2 Answers

I agree to BoltClock. Here is the sample code-

//Create a writer to write XML to the console.
XmlTextWriter writer = null;
writer = new XmlTextWriter (Console.Out);
//Use indentation for readability.
writer.Formatting = Formatting.Indented;
writer.Indentation = 4;
like image 132
Rhunita Avatar answered Sep 23 '25 01:09

Rhunita


If you're using XmlTextWriter to write to the file, you can set its Formatting property to Formatting.Indented before you write.

like image 41
BoltClock Avatar answered Sep 23 '25 01:09

BoltClock