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

如何编写XPath实现按tag分组筛选计数等于3的item节点

需求匹配XPath语句

你所需的XPath如下,完全兼容C#内置XML类库支持的XPath 1.0标准:
//item[count(//item[tag = current()/tag]) = 3]

逻辑说明

  • 内层筛选逻辑//item[tag = current()/tag]会匹配所有和当前待校验item节点的tag值完全一致的item节点
  • 用count()统计匹配到的节点总数,判断是否等于3,符合条件的item节点就会被最终选中
  • 你提供的示例XML运行该XPath,返回结果正好对应tag值为ABC的三个item:item1、item5、item6,符合你的需求

C#调用示例

基于XmlDocument的调用方式

using System.Xml;

// 加载XML
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("你的XML字符串"); // 也可以用Load方法加载本地XML文件

// 执行XPath查询
XmlNodeList targetItems = xmlDoc.SelectNodes("//item[count(//item[tag = current()/tag]) = 3]");

// 遍历处理结果
foreach (XmlNode item in targetItems)
{
    string tagVal = item["tag"].InnerText;
    string desc = item["description"].InnerText;
    // 后续业务处理逻辑
}

基于XDocument的调用方式

using System.Xml.Linq;
using System.Xml.XPath;

// 加载XML
XDocument xDoc = XDocument.Parse("你的XML字符串"); // 也可以用Load方法加载本地XML文件

// 执行XPath查询
var targetItems = xDoc.XPathSelectElements("//item[count(//item[tag = current()/tag]) = 3]");

// 遍历处理结果
foreach (XElement item in targetItems)
{
    string tagVal = item.Element("tag").Value;
    string desc = item.Element("description").Value;
    // 后续业务处理逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:06:03