2011-10-28 171 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之前出現的產品類型,那麼它將無法工作。 –

相關問題