How to pretty-print XML in C#

.NET programming topics
Post Reply
Cyclops
Lieutenant
Lieutenant
Posts: 71
Joined: Wed Jul 15, 2009 1:48 pm
Location: London

How to pretty-print XML in C#

Post by Cyclops » Thu Dec 31, 2009 9:33 am

It's easy to attractively format XML data as long as it's well-formed. Just load the XML into an XmlDocument. Then write the XML into an XmlTextWriter with formatting enabled. finally, extract the XML text from the XmlTextWriter.

Code: Select all

// Attractively format the XML with consistant indentation.

public static String PrettyPrint(String XML)
{
	String Result = "";

	MemoryStream MS = new MemoryStream();
	XmlTextWriter W = new XmlTextWriter(MS, Encoding.Unicode);
	XmlDocument D   = new XmlDocument();

	try
	{
		// Load the XmlDocument with the XML.
		D.LoadXml(XML);

		W.Formatting = Formatting.Indented;

		// Write the XML into a formatting XmlTextWriter
		D.WriteContentTo(W);
		W.Flush();
		MS.Flush();

		// Have to rewind the MemoryStream in order to read
		// its contents.
		MS.Position = 0;

		// Read MemoryStream contents into a StreamReader.
		StreamReader SR = new StreamReader(MS);

		// Extract the text from the StreamReader.
		String FormattedXML = SR.ReadToEnd();

		Result = FormattedXML;
	}
	catch (XmlException)
	{
	}

	MS.Close();
	W.Close();

	return Result;
}
Post Reply

Return to “.NET Programming”