我有一个文档,我正在替换某个节点的内部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节点。
我怎样才能做到这一点?
答案 0 :(得分:0)
与此类似的东西可能会成功。让架构为您完成缩进工作。
var node = document.SelectSingleNode("//ContainingNode");
node.RemoveAll();
using (var tr = XmlReader.Create(xmlReplacement))
{
while (tr.Read())
{
node.AppendChild(tr);
}
}
编辑:更改为删除obselete XmlTextReader
编辑2:更改为使用using