我有一个 XDocument 对象,ToString() 方法返回没有任何缩进的 XML。如何从中创建包含缩进 XML 的字符串?
编辑:我问如何创建内存中的字符串而不是写入文件。
编辑:看起来我不小心在这里问了一个技巧问题...ToString() 确实返回缩进的 XML。
XDocument doc = XDocument.Parse(xmlString);
string indented = doc.ToString();
从这里
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);
同一个汤又多了一种味道...;-)
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
Console.WriteLine(sw.ToString());
编辑:感谢约翰·桑德斯。这是一个应该更好地符合 MSDN 上的 Creating XML Writers 的版本。
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();