【发布时间】:2012-09-22 18:14:49
【问题描述】:
我正在尝试读取现有的 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);
}
【问题讨论】: