views:

318

answers:

4

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

+5  A: 

How do you save / write the XML back to a file ?

You can create an XmlWriter and pass it an XmlWriterSettings instance, where you set the Indent property to true:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

XmlWriter writer = XmlWriter.Create (outputStream, settings);
Frederik Gheysels
Well at the moment i dont write it to a file i just show it in a messagebox so all i got is a string..
Petoj
@Petoj - fine; write it to a StringWriter, then call ToString() on the StringWriter
Marc Gravell
+9  A: 

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

Jon Skeet
I have this app in my \bin directory, it is called "xmlpp" for XML pretty-print. invaluable.
Cheeso
A: 

Have a look at

XmlWriterSettings

http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.aspx

you can define Indent and IndentChars

tanascius
+1  A: 

You can load the string into an XDocument object and save it to a string again:

XDocument doc = XDocument.Load(new StringReader(xmlString));
StringWriter writer = new StringWriter();
doc.Save(writer);
string readable = writer.ToString();

That will give you the xml formatted this way:

<?xml version="1.0" encoding="utf-16"?>
<element1>
    <element2>some data</element2>
</element1>
Guffa