Another XML challenge: given an XML string, like:
<book><title>1984</title><author>Orwell</author></book>
What's the easiest way to display the XML in a friendly, indented way, like:
<book>
<title>
1984
</title>
<author>
Orwell
</author>
</book>
Here is my approach, let me know if you know of one better. Essentially, what I do is the following:
- Populate an XmlDocument with the XML data.
- Create an XmlTextWriter instance that writes to a StringWriter and set its
Formatting property to Formatting.Indented
- Save the XmlDocument's data to the XmlTextWriter via the
Save() method
- Get the prettily formatted XML by calling the StringWriter's
ToString() method.
Is there a more efficient way? It seems rather unfortunate to have to load the entire XML in an XmlDocument instance first. I guess one could use an XmlTextReader to read through each node, and then write it to the XmlTextWriter, but I don't see a method that does this for me automatically. Anywho, here's the code I use:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
StringWriter sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
writer.Formatting = Formatting.Indented;
xmlDoc.Save(writer);
Console.WriteLine(sw.ToString());