A quick and easy utility method which could be used for formatting an XML input string.

/// <summary>
/// Formats and returns the input Xml string.
/// </summary>
/// <param name="xmlString"></param>
public static string FormatXml( string xmlString )
{
    if ( !String.IsNullOrEmpty( xmlString ) )
    {
        XmlTextReader xmlRdr = new XmlTextReader( new
                                       StringReader( xmlString ) );

        StringWriter textWriter = new StringWriter();

        XmlTextWriter xmlWriter = new XmlTextWriter( textWriter );

        xmlWriter.Formatting = Formatting.Indented;

        xmlWriter.WriteNode( xmlRdr, false );
        return textWriter.ToString();
    }
    else
    {
        return string.Empty;
    }
}
Advertisements