能否用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
相关产品推荐
相关产品推荐

