How to delete specific nodes from an XElement?

How to delete specific nodes from an XElement?

You can try this approach:

var nodes = xRelation.Elements().Where(x => x.Element("Conditions") != null).ToList();

foreach(var node in nodes)
    node.Remove();

Basic idea: you can't delete elements of collection you're currently iterating.
So first you have to create list of nodes to delete and then delete these nodes.

 

研究发现,只有Elements()这种筛选的 IEnumerable<XElement>才有问题,没法进行Remove。

但是如果是Elements("add")或Elements("remove"),可以不用ToList()就正常删除的

 

另外还发现,如果有2个相同的节点,通过Elements("add")操作where过滤出来之后,只能删除一个

  <add assembly="System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />

  <add assembly="System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />

只有用了ToList(),然后再遍历,才可以正常删除

 

 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(53)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2020-05-11 ConcurrentDictionary测试
2020-05-11 Inside the Concurrent Collections: ConcurrentDictionary
2020-05-11 ArrayList and thread safe
2015-05-11 抽象工厂在ADO.Net中的应用
2015-05-11 Provider Pattern提供者模式和策略模式
2015-05-11 Strategy Pattern策略模式
点击右上角即可分享
微信分享提示