从的XDocument删除节点 [英] Removing nodes from XDocument
本文介绍了从的XDocument删除节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这将删除文档中的所有元素:
This removes all elements from the document:
XDocument document = XDocument.Load(inputFile);
foreach (XElement element in document.Elements())
{
element.Remove();
}
document.Save(outputFile);
这不会有任何影响:
XDocument document = XDocument.Load(inputFile);
foreach (XElement element in document.Elements())
{
//element.Remove();
foreach (XElement child in element.Elements())
child.Remove();
}
document.Save(outputFile);
我失去了一些东西在这里?由于这些都是的XDocument内元素的所有引用,不应更改生效?有一些其他的方式,我应该从一个XDocument被删除嵌套子?
Am I missing something here? Since these are all references to elements within the XDocument, shouldn't the changes take effect? Is there some other way I should be removing nested children from an XDocument?
谢谢!
推荐答案
显然,当你遍历 element.Elements()
,调用删除()
上一个孩子将导致枚举数产量突破
。遍历 element.Elements()了ToList()
解决了这一问题。
Apparently when you iterate over element.Elements()
, calling a Remove()
on one of the children causes the enumerator to yield break
. Iterating over element.Elements().ToList()
fixed the problem.
这篇关于从的XDocument删除节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文