Skip to main content
 首页 » 编程设计

xml之XPath:汇总问题时收集

2025年12月25日21yxwkf

我有一个具有以下结构的XML文件:

<person height="170"/> 
<person height="155"/> 
<person height="192"/> 
... 
<tree height="100"/> 
<tree height="300"/> 
<tree height="120"/> 


我需要返回所有至少有3棵树的人的身高在人的身高+-10范围内。

例如,如果一个人的身高为155,如果存在至少3棵树的高度在145到165之间,则该人将被返回。

我试图实现它,并得到了:

//person[count(//tree[@height >>>>>>is in range 10 to person's height<<<<<]) >= 3] 


我坚持执行内部部分。我尝试使用“当前”和“自我”,但似乎没有正确使用它们。

请您参考如下方法:

在这里可以使用for $me in .习惯用法:

//person[count(for $me in . return //tree[ 
    @height <= ($me/@height + 10) and @height >= ($me/@height - 10)]) >= 3] 


在这里,我使用单次迭代 for表达式捕获当前的 person(第一级谓词的 .),因此可以在第二级谓词(其中 .tree)。