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

能否用XPath 1.0定位符合特定规则的XML直接子节点?

XPath 1.0 表达式实现需求

针对指定节点(如mynode),满足要求的直接子节点查询表达式如下:

//mynode/*[
  count(child::*) >= 1
  and count(child::*) = count(child::*[local-name() = local-name(child::*[1])])
  and not(child::*[child::*])
]

表达式拆解说明

  • count(child::*) >= 1:确保目标子节点至少拥有一个子节点
  • count(child::*) = count(child::*[local-name() = local-name(child::*[1])]):验证目标子节点的所有子节点名称完全一致——通过对比「名称等于第一个子节点名称的子节点数量」和「总子节点数量」是否相等来实现
  • not(child::*[child::*]):确保目标子节点的所有子节点自身都没有子元素(即均为叶子节点)

示例验证

假设XML结构如下:

<mynode>
  <findthis>
    <same></same>
    <same></same>
  </findthis>
  <ignorethis>
    <diff1></diff1>
    <diff2></diff2>
  </ignorethis>
  <ignorethat>
    <haschild>
      <sub></sub>
    </haschild>
  </ignorethat>
</mynode>
  • findthis:三个条件全部满足,会被匹配
  • ignorethis:子节点名称不同,第二个条件不成立,被排除
  • ignorethat:子节点包含子元素,第三个条件不成立,被排除

内容的提问来源于stack exchange,提问作者a-a-h

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:55:37