在XML节点的所有子节点中搜索值并删除祖父节点

时间:2011-10-28 22:21:54

标签: c# xml linq

尝试使用

exportDoc.Root.Elements("string").Where(node => !(node.Element("product").HasElements) || node.Element("product").Element("type").Value != product).Remove();

删除我的XML文档中我没有搜索product字符串的节点。以下是我的XML结构示例:

<root>
   <string id = "Hithere">
      <product>
         <type>orange</type>
         <type>yellow</type>
         <type>green</type>
      <product>
      <element2/>
      <element3/>
    </string>
    <string id ="...">
     ...
     ... 
</root>

所以我需要查看每个product元素的string元素并在其中的每个type元素下查看字符串product的值(输入)发生这种情况的方法。目前,如果我正在搜索的product字符串与第一个type元素的值匹配,我的代码似乎只删除了节点。

重点是从xdoc中删除所有没有我要查找的产品的product元素下的字符串节点。

2 个答案:

答案 0 :(得分:1)

在您仍在枚举(延迟执行)时,不能删除()。

你需要更像的东西:

// untested
var toRemove = exportDoc.Root.Elements("string")
    .Where(node => !(node.Element("product").HasElements) ||
           node.Element("product").Element("type").Value != product).ToList();
toRemove.Remove();

答案 1 :(得分:1)

您需要稍微更改搜索条件:

var nodesToRemove = xDoc.Root
    .Elements("string")
    .Where(node =>
        !(node.Element("product").HasElements) ||
        node.Element("product").Elements("type").All(x => x.Value != product))
    .ToList();

这应匹配所有字符串:product:types与product值不同的元素(换句话说 - 如果至少有一个<type>与{{1}匹配},它不会被标记为删除)。

相关问题