Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从XDocument中删除节点_C#_Xml_Linq - Fatal编程技术网

C# 从XDocument中删除节点

C# 从XDocument中删除节点,c#,xml,linq,C#,Xml,Linq,这将从文档中删除所有元素: XDocument document = XDocument.Load(inputFile); foreach (XElement element in document.Elements()) { element.Remove(); } document.Save(outputFile); 这没有任何效果: XDocument 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中删除嵌套的子级


谢谢

下面是使用System.Xml.XPath的另一种方法的示例(更改XPath查询以满足您的需要):

const字符串xml=
@"
阿肯色州
加利福尼亚
弗吉尼亚州
";
XDocument doc=XDocument.Parse(xml);
doc.XPathSelectElements(“//xml/country/states/state[.='arkansas']”)。ToList()
.ForEach(el=>el.Remove());;
Console.WriteLine(doc.ToString());
Console.ReadKey(true);

显然,当您迭代
元素时。元素()
,对其中一个子元素调用
Remove()
,会导致枚举数
产生中断。迭代
element.Elements().ToList()
修复了该问题。

使用
XDocument
时,请尝试以下操作:

XDocument document = XDocument.Load(inputFile);
foreach (XElement element in document.Elements())
{
     document.Element("Root").SetElementValue(element , null);
}
document.Save(outputFile)
问候,,
托德

你调试过代码了吗?您确定element.Elements()正在返回子元素吗?只是想了解更多有关您所看到的情况的信息。@jrista它返回子元素,但问题似乎是枚举数在
.Remove()
之后的行为有所不同。是的,这是我所期望的。枚举数通常在修改集合时抛出异常,因为它们非常依赖于基础集合的稳定性才能正常运行。实际上,我很惊讶您在使用foreach/枚举器时删除节点后可以继续。我通常会建议使用while循环(或者可能是for…,但这更复杂),而不是foreach。@jrista如果这样说,它会更有意义。无声的失败总是让我头疼:/是的,我讨厌无声的失败。我真的很惊讶这里会发生这种情况,通常,.NET中的迭代+集合修改意味着抛出异常。我在reflector中深入研究了XDocument代码,而.Remove()的工作方式实际上是循环的,它涉及到在某一点上创建一个内部列表。我猜这就是为什么删除成功而没有抛出…但它肯定会打乱枚举,因为集合的状态发生变化,而枚举器不知道。这是XPath特有的吗?@Neo以什么方式?如上所述,当基础集合更改时,大多数枚举数都会中断。是的,我知道InvalidOperationException通常会发生。我的问题是关于
收益率突破
。这是XPath相对于@jrista的注释re-silent失败所特有的吗?
XDocument document = XDocument.Load(inputFile);
foreach (XElement element in document.Elements())
{
     document.Element("Root").SetElementValue(element , null);
}
document.Save(outputFile)