使用XDocument根据重复identifier段匹配值移除XML指定Patient元素
问题原因
你编写的代码失效核心有两点:
- 第一段代码中
x.Element("identifier")仅会取当前Patient节点下的第一个identifier子节点,且未做空值兼容,存在空引用风险; - 第二段代码存在语法错误,
("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
相关产品推荐
相关产品推荐

