如何在c#中从XDocument创建缩进的XML字符串?

我有一个XDocument对象,ToString()方法返回XML而没有任何缩进。 如何从包含缩进的XML创建字符串?

编辑:我问的是如何创建一个内存字符串而不是写出文件。

编辑:看起来我不小心在这里问了一个技巧问题… ToString()确实返回缩进的XML。

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

从这里开始

 XmlDocument doc = new XmlDocument(); doc.LoadXml("wrench"); // 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); 

还有一种同样的汤的味道… 😉

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

编辑:感谢John Saunders 。 这个版本应该更好地符合在MSDN上创建XML Writer 。

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

要使用XDocument(而不是XmlDocument)创建字符串,您可以使用:

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

编辑:更新以使用XmlWriter.CreateStringBuilder以及良好的表单( using )。