JC.
JC.

Reputation: 11801

How do you create an indented XML string from an XDocument in c#?

I have an XDocument object and the ToString() method returns XML without any indentation. How do I create a string from this containing indented XML?

edit: I'm asking how to create an in memory string rather than writing out to a file.

edit: Looks like I accidentally asked a trick question here... ToString() does return indented XML.

Upvotes: 27

Views: 22472

Answers (4)

DocMax
DocMax

Reputation: 12164

To create a string using an XDocument (rather than an XmlDocument), you can use:

XDocument doc = new XDocument(
    new XComment("This is a comment"),
    new XElement("Root",
        new XElement("Child1", "data1"),
        new XElement("Child2", "data2")
    )
);

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlTextWriter.Create(sb, settings)) {
    doc.WriteTo(writer);
    writer.Flush();
}
string outputXml = sb.ToString();

Upvotes: 6

Fabrizio C.
Fabrizio C.

Reputation: 1564

Just one more flavor of the same soup... ;-)

StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
Console.WriteLine(sw.ToString());

Edit: thanks to John Saunders. Here is a version that should better conform to Creating XML Writers on MSDN.

using System;
using System.Text;
using System.Xml;
using System.Xml.Linq;

class Program
{
    static void Main(string[] args)
    {
        XDocument doc = new XDocument(
        new XComment("This is a comment"),
        new XElement("Root",
            new XElement("Child1", "data1"),
            new XElement("Child2", "data2")
            )
            );

        var builder = new StringBuilder();
        var settings = new XmlWriterSettings()
        {
            Indent = true
        };
        using (var writer = XmlWriter.Create(builder, settings))
        {
            doc.WriteTo(writer);
        }
        Console.WriteLine(builder.ToString());
    }
}

Upvotes: 7

John Saunders
John Saunders

Reputation: 161773

XDocument doc = XDocument.Parse(xmlString);
string indented = doc.ToString();

Upvotes: 28

tomfanning
tomfanning

Reputation: 9660

From here

XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");

// Save the document to a file and auto-indent the output.
XmlTextWriter writer = new XmlTextWriter("data.xml",null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);

Upvotes: 9

Related Questions