【问题标题】:How to remove a child node如何删除子节点
【发布时间】:2015-04-30 02:46:48
【问题描述】:

我想删除具有我从 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();                            

代码执行但没有任何反应。

【问题讨论】:

  • 当然什么也没发生。您正在创建一个临时对象并从中删除内容。你没有分配它或任何东西。
  • 我怎样才能实现删除相应节点的目标
  • 尝试 .equals 并忽略大小写,向我们展示更多代码如何读取 xml 和其他内容。检查 xmlDocument.Descendants("user").Where(x => (string)x.Attribute("Id") == usrCookieId) .Elements("city") 计数

标签: c# xml linq


【解决方案1】:

试试这个:-

如您所见,我从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");

【讨论】:

  • “试试这个”不是一个好的答案。至少我是这么说的。
  • 对我来说,问题中的原始代码工作得很好。无需修改。可能参数根本不匹配?
  • @MatthewFrontino 但回复的作者有 7.3K 代表
  • @Rahul 我试过了,但它不起作用。它只是执行但什么也没删除
  • @MatthewFrontino - 是的,兄弟,请耐心等待几分钟,包括 Jon Skeet 爵士在内的每个人都会在发布后更新他的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
  • 2011-02-09
  • 1970-01-01
  • 1970-01-01
  • 2013-11-09
相关资源
最近更新 更多