2011-10-28 175 views
1

尝试使用搜索XML节点的所有子节点的值,并移除祖父节点

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> 

所以我需要每个string元件的product元件之下,并在每个在其中的type元素来看看是否串product(输入的值,以该方法在哪里包含)发生。目前,如果我要搜索的product字符串与第一个type元素的值匹配,它看起来像我的代码只会删除该节点。

整个问题是要删除此xdoc中没有我要查找的产品的product元素下的所有字符串节点。

回答

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值不同(换句话说 - 如果至少有一个<type>将与您的product相匹配,则不会标记为删除)。

+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(); 
+0

谢谢你的回复。我认为问题是'.Element(“type”)'只返回第一个'type'元素。因此,如果只有一种产品类型,它就可以工作,但如果有多种产品类型,特别是在XML之前出现的产品类型,那么它将无法工作。 –

相关问题