我有一个文档,我正在替换某个节点的内部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节点的close在同一行上的close节点。
我怎么才能把这事做好呢?
发布于 2011-12-13 01:18:16
类似这样的东西可能会起到作用。让模式为您做缩进工作。
var node = document.SelectSingleNode("//ContainingNode");
node.RemoveAll();
using (var tr = XmlReader.Create(xmlReplacement))
{
while (tr.Read())
{
node.AppendChild(tr);
}
}EDIT:更改为删除过时的XmlTextReader EDIT 2:更改为使用using
https://stackoverflow.com/questions/8477957
复制相似问题