Display Formatted XML

From Relyimah

Jump to: navigation, search

C# Function to display XML nicely formatted with tabs, etc.

C# Source:

/// <summary>
/// Returns formatted xml string (indent and newlines) from unformatted XML
/// string for display in eg textboxes.
/// </summary>
/// <remarks>Source: http://www.codeproject.com/soap/FormattingXML.asp </remarks>
/// <param name="sUnformattedXml">Unformatted xml string.</param>
/// <returns>Formatted xml string and any exceptions that occur.</returns>
protected string sfnFormatXml(string sUnformattedXml)
{
    //load unformatted xml into a dom
    XmlDocument xd = new XmlDocument();
    xd.LoadXml(sUnformattedXml);
 
    //will hold formatted xml
    StringBuilder sb = new StringBuilder();
 
    //pumps the formatted xml into the StringBuilder above
    StringWriter sw = new StringWriter(sb);
 
    //does the formatting
    XmlTextWriter xtw = null;
 
    try
    {
        //point the xtw at the StringWriter
        xtw = new XmlTextWriter(sw);
 
        //we want the output formatted
        xtw.Formatting = Formatting.Indented;
 
        //get the dom to dump its contents into the xtw
        xd.WriteTo(xtw);
    }
    finally
    {
        //clean up even if error
        if (xtw != null)
            xtw.Close();
    }
 
    //return the formatted xml
    return sb.ToString();
}
Personal tools