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

后端 未结 4 1338
萌比男神i
萌比男神i 2020-12-07 00:32

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 aski

4条回答
  •  庸人自扰
    2020-12-07 01:16

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

提交回复
热议问题