27

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.

JC.
  • 11,561
  • 11
  • 41
  • 50
  • Can you post your code? The only way I can get XDocument.ToString to NOT indent the XML is when I explicitly pass in SaveOptions.DisableFormatting to the ToString method. – Joel Mueller Mar 03 '10 at 22:26
  • I tried the answers here. They had no effect (still uses spaces). Using .Net 4 (not client). – Sellorio May 14 '13 at 02:05
  • Related: http://stackoverflow.com/questions/1123718/format-xml-string-to-print-friendly-xml-string – CJBS Apr 13 '16 at 18:23

4 Answers4

27
XDocument doc = XDocument.Parse(xmlString);
string indented = doc.ToString();
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • 12
    This works fine. `XDocument.ToString()` formats with indentation by default. To get unformatted output, you have to go out of your way by calling `.ToString(SaveOptions.DisableFormatting)` – Joel Mueller Mar 03 '10 at 22:25
  • 2
    I was actually looking for disabling. Thanks @JoelMueller – Eric Jun 02 '15 at 19:27
9

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);
tomfanning
  • 9,552
  • 4
  • 50
  • 78
7

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());
    }
}
Community
  • 1
  • 1
Fabrizio C.
  • 1,544
  • 10
  • 12
5

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();

Edit: Updated to use XmlWriter.Create and a StringBuilder and good form (using).

DocMax
  • 12,094
  • 7
  • 44
  • 44
  • 1
    -1: Do not use new XmlTextWriter() or new XmlTextReader() past .NET 1.1. Use XmlWriter.Create() or XmlReader.Create() – John Saunders Mar 03 '10 at 21:58
  • 1
    Thanks, I'd missed that. I updated the sample accordingly (and reduced complexity with a StringBuilder at the same time!) – DocMax Mar 03 '10 at 22:15
  • FYI, on review, I still want to keep my downvote because you didn't use a `using` block. – John Saunders Aug 16 '13 at 19:24
  • 2
    @JohnSaunders: Thanks again and updated again. I suspect I was originally trying to focus on the basic behavior, but sloppy samples tend to end up in sloppy code somewhere else. – DocMax Aug 16 '13 at 20:17