Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to get indented XML with line breaks from XmlDocument?

When I build XML up from scratch with XmlDocument, the OuterXml property already has everything nicely indented with line breaks. However, if I call LoadXml on some very "compressed" XML (no line breaks or indention) then the output of OuterXml stays that way. So ...

What is the simplest way to get beautified XML output from an instance of XmlDocument?

like image 202
Neil C. Obremski Avatar asked Oct 15 '08 02:10

Neil C. Obremski


People also ask

How do I indent text in XML?

In Text mode when you select one of the format and indent actions (Document > Source > Format and Indent, Document > Source > Indent Selection, or Document > Source > Format and Indent Element).

What is indent XML?

Indenting XML tags is never required for parsing. However, the point of XML is to be human as well as machine readable, so indentation is generally worth having, as it makes it far easier for human readers to work with and take in the structure at a glance.

Which method of the XmlDocument class takes XML as string while loading?

Use XmlDocument. Load() method to load XML from your file. Then use XmlDocument. InnerXml property to get XML string.

How do I dispose of XmlDocument?

The XmlDocument class does not implement IDisposable , so there's no way to force it to release it's resources at will. If you need to free that memory the only way to do that would be xmlDocument = null; and garbage collection will handle the rest.


2 Answers

Based on the other answers, I looked into XmlTextWriter and came up with the following helper method:

static public string Beautify(this XmlDocument doc) {     StringBuilder sb = new StringBuilder();     XmlWriterSettings settings = new XmlWriterSettings     {         Indent = true,         IndentChars = "  ",         NewLineChars = "\r\n",         NewLineHandling = NewLineHandling.Replace     };     using (XmlWriter writer = XmlWriter.Create(sb, settings)) {         doc.Save(writer);     }     return sb.ToString(); } 

It's a bit more code than I hoped for, but it works just peachy.

like image 137
Neil C. Obremski Avatar answered Sep 20 '22 21:09

Neil C. Obremski


As adapted from Erika Ehrli's blog, this should do it:

XmlDocument doc = new XmlDocument(); doc.LoadXml("<item><name>wrench</name></item>"); // Save the document to a file and auto-indent the output. using (XmlTextWriter writer = new XmlTextWriter("data.xml", null)) {     writer.Formatting = Formatting.Indented;     doc.Save(writer); } 
like image 35
DocMax Avatar answered Sep 18 '22 21:09

DocMax