I’m dealing with some gnarly HTML. Here’s a stylized example of the ancestry of a given element:
/html/body/foo/bar/baz/quux/b
I have a reference to body in my code and b is the context element for my XPath query. In the above example how do I find foo? More descriptively, how do I find the first element in a given ancestry which is the child of another given element? The elements between body and b are unknown and varied in type and depth at runtime. I can do this outside of XPath by iterating over the ancestors from b until I get to body but I’m wondering if there’s some XPath ancestor magic to find this relative reference.
Use:
this selects the element that is the first element child of
bodythat is the first ancestorbodyof the context node.Even if you know that there are no nested
bodyelements, the above is slightly more efficient than:because evaluating this last expression, all ancestors will be tested for being a
body.UPDATE:
In a comment the OP clarified:
In XPath 1.0 this is q direct substitution into the well-known Kayessian formula for node-set intersection:
In this case we substitute
$ns1withancestor::*and $ns2 with/*/body/*:In XPath 2.0 this is easier, using the
intersectoperator: