【发布时间】:2011-12-12 17:03:32
【问题描述】:
我有一个文档,我要在其上替换某个节点的内部 XML:
var xmlReplacement = File.ReadAllText(path); // this xml is well formatted with indentations itself, but not indented at the correct level for the document it's about to be inserted into
var document = new XmlDocument();
document.PreserveWhitespace = true;
document.Load(path);
// replace inner xml of ContainingNode
var node = document.SelectSingleNode("//ContainingNode");
node.InnerXml = xmlReplacement;
// write back to the output file
using (var writer = new XmlTextWriter(path, null))
{
writer.Formatting = Formatting.Indented;
document.WriteTo(writer);
}
我最终得到了新的内部 xml 非缩进(一直到左侧),并且关闭节点与我的替换 xml 节点的关闭位于同一行。
我怎样才能做到这一点?
【问题讨论】:
-
也许尝试将 xmlReplacement 解析为新的 XmlDocument 并使用 node.RemoveAll 和 node.AppendChild 添加替换?
-
你为什么关心缩进? XML 不关心,那你为什么要关心呢?
-
因为人们必须使用这个文件。如果有人运行替换代码并将文件签入源代码管理会发生什么?然后其他人手动打开 xml 文件,编辑某些内容并重新格式化它?现在差异化是一件很痛苦的事情。
标签: .net xml xmldocument xmlwriter