我正在尝试读取现有的 XML 文件,修改一堆节点的 InnerText 和 Attribute 值,然后将更改保存回文件。
我正在使用以下代码。保存 XML 文件时,它会弄乱格式。例如,某些节点之间的换行符消失了。如何保留(或重新格式化以及格式化和缩进)XML 文件?
XmlDocument xDoc = new XmlDocument();
using (XmlReader xRead = XmlReader.Create(strXMLFilename))
{
xDoc.Load(xRead);
}
//Makes changes to a few nodes
XmlWriterSettings xwrSettings = new XmlWriterSettings();
xwrSettings.IndentChars = "\t";
xwrSettings.NewLineHandling = NewLineHandling.Entitize;
xwrSettings.Indent = true;
xwrSettings.NewLineChars = "\n";
using (XmlWriter xWrite = XmlWriter.Create(strXMLFilename, xwrSettings))
{
xDoc.Save(xWrite);
}
请您参考如下方法:
好的,默认情况下,XmlDocument 对象会忽略空格。我不得不强制它像这样保留空白 —
xDoc.PreserveWhitespace = true;
砰!问题解决了!
