'detect a circle via xpath

Given a XML document such as the following one, when each "a" has a unique identifier and each "b" nested in it references an instance of "a":

<a id="1">
  <b ref="2">
  </b>
</a>
<a id="2">
 <b ref="1">
 </b>
</a>

I'd like to find a way to find the "a"'s who have a "b" that references to an "a", who in its turn has a "b" that references to the first "a". I know it's quite a clumsy way to say this, but what I mean is that I'm looking for a way to find a circle (1 has a "b" instance pointing to 2, when 2 has a "b" instance pointing to 1)

Is there a way to put it into a XPath query?



Solution 1:[1]

Since XPath 1.0 does not support current() it is not really possible(see this question as well), the closest I can get is this:

//a[b[@ref[.= ancestor::a/following-sibling::a[b[@ref[.=ancestor::a/preceding-sibling::a/@id]]]/@id]]]

It will match a with b/@ref that equals following a/@id with b/@ref that equals preceding a/@id`

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Siebe Jongebloed