我有一个XDocument对象,ToString()方法返回XML而没有任何缩进.如何从包含缩进的XML创建字符串?
编辑:我问的是如何创建一个内存字符串而不是写出文件.
编辑:看起来我不小心在这里问了一个技巧问题... ToString()确实返回缩进的XML.
Joh*_*ers 24
XDocument doc = XDocument.Parse(xmlString);
string indented = doc.ToString();
Run Code Online (Sandbox Code Playgroud)
从这里开始
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);
Run Code Online (Sandbox Code Playgroud)
小智 7
还有一种同样的汤的味道... ;-)
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
Console.WriteLine(sw.ToString());
Run Code Online (Sandbox Code Playgroud)
编辑:感谢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());
}
}
Run Code Online (Sandbox Code Playgroud)
要使用 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();
Run Code Online (Sandbox Code Playgroud)
编辑:更新为使用XmlWriter.Create和StringBuilder良好的形式(using)。
| 归档时间: |
|
| 查看次数: |
16393 次 |
| 最近记录: |