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>
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
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.
Thanks,
Michael
Maybe this XPath 2.0 expression answers your question :
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).