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

后端 未结 4 1340
萌比男神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:12

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

提交回复
热议问题