查找符合条件的最近的祖先/兄弟姐妹 [英] Find nearest ancestor/sibling that matches criteria
问题描述
我有 XML,它由容器节点组成,其中包含各种子节点,包括其他容器节点.示例 XML 看起来像...
I have XML that is composed of container nodes holding various child nodes including other container nodes. Sample XML would look like...
<CONTAINER>
<SEARCHFOR />
<ITEM/>
<ITEM/>
<ITEM/>
<ITEM/>
<ITEM/>
<CONTAINER>
<SEARCHFOR />
<ITEM/>
<ITEM/>
<CONTAINER>
<SEARCHFOR />
<ITEM id="1" />
<ITEM/>
<ITEM/>
<CONTAINER>
<ITEM id="2" />
</CONTAINER>
</CONTAINER>
</CONTAINER>
</CONTAINER>
我想找到与 id=2 的 ITEM 最接近(在范围内)的 SEARCHFOR 节点.SEARCHFOR 节点可以是 ITEM 的前同级或祖先 CONTAINER 节点的子级.我有一个 XPath 表达式,可以定位范围内与条件匹配的所有 SEARCHFOR 节点,但我似乎无法让它只返回最近的单个元素.
I'd like to find the SEARCHFOR node that is nearest (in scope) to the ITEM having id=2. The SEARCHFOR node can be a preceding-sibling of ITEM or a child of an ancestor CONTAINER node. I have an XPath expression that can locate all SEARCHFOR nodes that are in scope that match the criteria, but I can't seem to get it to only return the single element that is nearest.
//ITEM[@id="2"]/ancestor::CONTAINER/SEARCHFOR
我正在 Sketchpath 中进行测试,并将使用可以处理 XPath 2.0 的 XML 解析器在 Delphi 中实现它,因此语法也是可以接受的.我可以通过获取我的结果并使用 Delphi 来获得感兴趣的结果在代码中完成此操作,但如果可能的话,我真的需要在 XPath 本身中完成此操作以进行我的实现.任何帮助表示赞赏.
I am testing in Sketchpath and will be implementing this in Delphi using an XML parser that can handle XPath 2.0 so that syntax is also acceptable. I can do this in code by getting my results and using Delphi to get the one of interest, but if at all possible I really need this to be done within the XPath itself for my implementation. Any help is appreciated.
谢谢,迈克尔
推荐答案
也许这个 XPath 2.0 表达式可以回答你的问题:
Maybe this XPath 2.0 expression answers your question :
(//ITEM[@id='2']/(ancestor::CONTAINER/SEARCHFOR|preceding-sibling::SEARCHFOR))[last()]
它的工作原理是按文档顺序构建一系列元素,然后选择最后一个,也就是根据您的描述,最接近的(如果我没猜错的话).
It works by building a sequence of elements in document order, then it chooses the last one, which is, given your description, the nearest (if I get you right).
这篇关于查找符合条件的最近的祖先/兄弟姐妹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!