You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用XDocument根据重复identifier段匹配值移除XML指定Patient元素

问题原因

你编写的代码失效核心有两点:

  1. 第一段代码中x.Element("identifier")仅会取当前Patient节点下的第一个identifier子节点,且未做空值兼容,存在空引用风险;
  2. 第二段代码存在语法错误,("system").Attribute("value")未关联到遍历的identifier节点,逻辑完全不成立。

可直接运行的解决方案

模糊包含匹配(符合你的业务需求)

xdoc.Root
    .Elements("Bundle")
    .Elements("entry")
    .Elements("resource")
    .Elements("Patient")
    .Elements("contained")
    .Elements("Patient")
    .Where(p => p.Elements("identifier")
        .Any(id => id.Element("system")?.Attribute("value")?.Value.Contains("remove-this-Patient") == true)
    )
    .Remove();

精确值匹配(可选)

如果需要完全匹配system属性值,可以使用如下写法:

xdoc.Root
    .Elements("Bundle")
    .Elements("entry")
    .Elements("resource")
    .Elements("Patient")
    .Elements("contained")
    .Elements("Patient")
    .Where(p => p.Elements("identifier")
        .Any(id => (string)id.Element("system")?.Attribute("value") == "http://example.com/remove-this-Patient")
    )
    .Remove();

写法说明

  • 使用Elements代替Descendants可以严格匹配你指定的XML路径层级,避免误匹配其他位置的同名节点,执行效率也更高
  • 用Any()遍历当前Patient下所有identifier节点,只要有任意一个system属性符合条件就会命中,完美解决多identifier重复节点的匹配问题
  • ?.空值传播运算符可以兼容节点缺失的场景,避免抛出空引用异常

内容的提问来源于stack exchange,提问作者David

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:06:07