Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 703
Peter Avatar asked Feb 26 '09 10:02

Peter


1 Answers

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.)

like image 162
Jon Skeet Avatar answered Sep 24 '22 10:09

Jon Skeet