【问题标题】:XmlWriter messing formatting when saving XML保存 XML 时 XmlWriter 搞乱格式
【发布时间】:2012-09-22 18:14:49
【问题描述】:

我正在尝试读取现有的 XML 文件,修改一组节点的 InnerTextAttribute 值,然后将更改保存回文件。

我正在使用以下代码。保存 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);
}

【问题讨论】:

    标签: c# .net xml xmlwriter


    【解决方案1】:

    好的,XmlDocument 对象默认忽略空格。我不得不强迫它像这样保留空白 -

    xDoc.PreserveWhitespace = true;
    

    和 BAM!问题解决了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      • 2020-07-27
      • 2020-12-13
      • 1970-01-01
      • 1970-01-01
      • 2012-03-19
      • 2012-07-12
      相关资源
      最近更新 更多