在VS2008中使用.Net 3.5 SP1我有一个XmlDocument并尝试将其写入文件:
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>
如何在从.Net写入文件之前整理我的XML?!
答案 0 :(得分:2)
我通过将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);
}