XmlWriterSettings, xmltextwwriter, XmlWriter不格式化输出?!没有新行,没有缩
本文关键字:新行 输出 xmltextwwriter XmlWriter 格式化 XmlWriterSettings | 更新日期: 2023-09-27 18:09:53
在VS2008中使用。net 3.5 SP1,我有一个XmlDocument,并尝试将其写入file:
using (XmlTextWriter tw = new XmlTextWriter(outXmlFileName, System.Text.Encoding.UTF8))
{
tw.Formatting = Formatting.Indented;
tw.Indentation = 3;
tw.IndentChar = ' ';
tw.QuoteChar = '''';
doc.Save(tw);
}
和
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(outXmlFileName, settings))
{
doc.Save(writer);
}
从文档http://msdn.microsoft.com/en-us/library/kkz7cs0d.aspx中不清楚的是,如果我应该使用。net 2之上的XmlWriter.Create(),无论如何都没有方法格式化输出!我只得到XmlDocument实例中的内容:
<?xml version='1.0' encoding='utf-8'?>
<root>
<node1 />
<node2 value='Data' />
<node3 value='ID' /><node4><item>
<from value='1 Jan 1870' />
<id value='PF' />
<to value='1 Jan 1940' /></item></node4>
</root>
我怎么能整理我的XML之前写它的文件从。net ?
我通过将XML加载到第二个中间XmlDocument实例中来使其工作,因此它忘记了原始的空白:
XmlWriterSettings settings = new XmlWriterSettings(); // http://msdn.microsoft.com/en-us/library/kkz7cs0d(VS.85).aspx
settings.Indent = true;
XmlDocument doc2 = new XmlDocument();
doc2.LoadXml(doc.OuterXml);
using (XmlWriter writer = XmlWriter.Create(outXmlFileName, settings))
{
doc2.Save(writer);
}