2011-02-22 71 views
0

我想使用LINQ to XML從XML文檔中刪除子元素。使用LINQ to XML從XML中刪除子元素

樣本XML:

<MainElement> 
<otherelement /> 
<removeElement att='1'> 
<removeElement att='2'> 
<removeElement att='3'> 
<removeElement att='4'> 
</MainElement> 

我想輸出是

<MainElement> 
<otherelement /> 
<removeElement att='2'> 
</MainElement> 

結構(架構)應保持原樣,並且所選擇的元件應該保持在XML文檔。

,我試圖查詢幫助我找到該元素從XML,但是,我怎麼維護XML結構

+0

請參考http://stackoverflow.com/questions/1648221/deleteing-whole-sections-of-my-xml-file-in-c/1648232#1648232一個解決類似涉及從文檔中過濾和刪除子元素的問題。 – 2011-02-22 19:18:43

+0

這隻適用於單一元素! – genericuser 2011-02-22 19:25:51

回答

1

編寫一個查詢,找到你要刪除,並刪除它們的節點。

XDocument doc = ...; 
doc.Root 
    .Elements("removeElement") 
    .Where(e => (int)e.Attribute("att") != 2) 
    .Remove(); // removes all elements in this query