2015-04-29 281 views
1

我想要刪除城市節點的價值,我得到從Request.QueryString["removect"],並在特定的用戶ID說<user Id="4/29/2015 6:11:34 PM">如何刪除子節點

<Users> 
    <user Id="4/28/2015 11:29:44 PM"> 
    <city>Moga</city> 
    <city>Rupnagar</city> 
    <city>Fatehgarh Sahib</city> 
</user> 
    <user Id="4/29/2015 10:59:06 AM"> 
    <city>Bathinda</city> 
    <city>Pathankot</city> 
    </user> 
    <user Id="4/29/2015 6:11:34 PM"> 
    <city>Pathankot</city> 
    <city>Tarn Taran</city> 

    </user> 
</Users> 

我使用來完成,這是的代碼如下:

xmlDocument.Descendants("user").Where(x => (string)x.Attribute("Id") == usrCookieId) 
.Elements("city") 
.Where(x => (string)x.Value ==Request.QueryString["removect"]).Remove();        

代碼執行,但沒有任何反應。

+2

當然沒有任何反應。您正在創建一個臨時對象並從中刪除東西。你沒有分配它或任何東西。 – Gigi

+0

我怎樣才能完成我的目標,刪除適當的節點 –

+0

嘗試.equals並忽略大小寫,向我們展示更多代碼如何閱讀XML和東西。檢查xmlDocument.Descendants(「user」)。其中(x =>(string)x.Attribute(「Id」)== usrCookieId) .Elements(「city」)count – din

回答

0

試試這個: -

我已經開始用city,你可以看到,然後與其父即user過濾你的病情,並自x由城市元素,我們可以直接過濾。現在,我使用First來獲取只有第一個匹配元素,一旦我們有我們需要使用的city節點是Remove

XDocument xmlDocument= XDocument.Load("YourXMLFile"); 
xmlDocument.Descendants("city").First(x => (string)x.Parent.Attribute("Id") == usrCookieId 
      && (string)x == Request.QueryString["removect"]).Remove(); 
xmlDocument.Save("YourXMLFilePath"); 
+0

「試試這個」不是一個好的答案。這至少是我所知道的。 –

+0

對於我來說,問題中的原始代碼工作得很好。不需要修改。可能參數根本不匹配任何東西? – Nikolay

+0

@MatthewFrontino尚未作出迴應的作者有7.3K代表 –