Click here to Skip to main content
Click here to Skip to main content

Formatting XML - A Code snippet

By , 14 Jan 2007
 

Introduction

I know this is basic stuff for many here, but as I couldn't find any similar article on this site I thought Id share this useful code snippet for those not so au-fait with the Xml classes.

Basically, I wanted a quick and easy way to get from a non-formatted string of XML, to something that could be nicely displayed in a textbox (ie with indenting and line breaks) without too much mucking about.

Using the code

Simple. Just call the method and display the result, eg. in a Windows forms textbox. Displaying in Webform elements may need the newline characters changed which can be done easily using String.Replace.

The code:

using System.Text;
using System.Xml;

. . .

/// <summary>
/// Returns formatted xml string (indent and newlines) from unformatted XML
/// string for display in eg textboxes.
/// </summary>
/// <param name="sUnformattedXml">Unformatted xml string.</param>
/// <returns>Formatted xml string and any exceptions that occur.</returns>

private string FormatXml(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();
}

Happy coding!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Ian Randell
United Kingdom United Kingdom
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberKoushikAmit20 Mar '13 - 18:32 
Its give the absolute solution what I have actually wanted. Thanks man!......keep it up and give us the greatest solution.
GeneralMy vote of 5memberDuc Huy Nguyen25 May '12 - 9:29 
Helpful for my JSON to XML project
QuestionVB.Net versionmemberFidoDildo11 Jul '11 - 4:31 
For the VB.Net N00bs: Poke tongue | ;-P
 
    Private Function formatXML(_text As String)
 
        Dim _doc As New Xml.XmlDocument
        _doc.LoadXml(_text)
 
        Dim _stringBldr As New StringBuilder
        Dim _stringWrtr As New StringWriter(_stringBldr)
 
        Dim _xmlTextWrtr As Xml.XmlTextWriter = Nothing
 
        Try
 
            _xmlTextWrtr = New Xml.XmlTextWriter(_stringWrtr)
            _xmlTextWrtr.Formatting = Xml.Formatting.Indented
            _doc.WriteTo(_xmlTextWrtr)
 
        Finally
 
            If _xmlTextWrtr IsNot Nothing Then _xmlTextWrtr.Close()
 
        End Try
 
        Return _stringBldr.ToString()
 
    End Function

GeneralMy vote of 5memberearnshaw194324 May '11 - 3:00 
Simple and easy to understand.
GeneralMy vote of 5memberfreedeveloper22 Dec '10 - 11:06 
Very good and simple solution. thanks for share it. I made a small modification to get xml without root, simply add a provisional root tag to the string and I eliminated it when the routine ended the format.
GeneralThanks for Sharing thismemberjgdean1429 Sep '09 - 12:27 
The simple things are always the best.
 
Watch me now I'm gonna eat the label
-Frank Zappa

GeneralU made my daymemberperren25 Mar '09 - 12:15 
Dear Ian,
 
U solved a problem that I spent some hours trying to solv, it was exactly what I was looking for !
 
Thanks again Smile | :)
 
P-M W

GeneralThanksmembersumit703412 Feb '09 - 18:51 
It was really useful for me
GeneralMy vote of 1memberKevin Dance4 Dec '08 - 2:50 
Read the artical (or lack of it) and I don't need to say any more
GeneralThxmemberbinabic17 Apr '08 - 20:55 
Useful for me, thank you for your work and sharing Smile | :)
GeneralQl snippetmemberPredrag Tomasevic30 Oct '07 - 15:59 
Wink | ;)
GeneralNice!membercraigg7516 Jan '07 - 4:23 
Very elegant code -- simple yet powerful. Great job! Smile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 14 Jan 2007
Article Copyright 2007 by Ian Randell
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid