2015-04-29 174 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代表 –