Search code examples
c#.netxmlvb.nettext-formatting

Make xml more readable


Is there any way to take an xml string in .net and make it easyer to read? what i mean is can i convert this:

<element1><element2>some data</element2></element1>

to this:

<element1>
    <element2>
        some data
    </element2>
</element1>

is there any built in class for this? as sql server 2005 seems to remove all formatting on xml to save space or some thing...


Solution

  • If you're using .NET 3.5, you can load it as an XDocument and then just call ToString() which will indent it appropriately. For example:

    using System;
    using System.Xml.Linq;
    
    public class Test
    {
        static void Main()
        {
            string xml = "<element1><element2>some data</element2></element1>";
    
            XDocument doc = XDocument.Parse(xml);
            xml = doc.ToString();
            Console.WriteLine(xml);
        }
    }
    

    Result:

    <element1>
      <element2>some data</element2>
    </element1>
    

    If you're writing it to a file or other stream, then XDocument.Save will (by default) indent it too.

    (I believe XElement has all the same features, if you don't really need an XDocument.)