Format an XML string as 'Pretty' - line breaks, indents etc

1. Put the following method in your project:


public static String PrettyPrint(String XML)
{
	String Result = "";
	System.IO.MemoryStream MS = new System.IO.MemoryStream();
	System.Xml.XmlTextWriter W = new System.Xml.XmlTextWriter(MS, System.Text.Encoding.Unicode);
	System.Xml.XmlDocument D = new System.Xml.XmlDocument();

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

                W.Formatting = System.Xml.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.
                System.IO.StreamReader SR = new System.IO.StreamReader(MS);

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

                Result = FormattedXML;
	}
	catch (System.Xml.XmlException)
	{
	}

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

	return Result;
}

2. Wherever you need formatted 'pretty' XML, such as in a form element of an application, call the function:


	SomeTextBox.Text = PrettyPrint(xmlString);

And that is all there is! Pretty XML!