If you want to select all h5
that are exactly 4 levels below their h1 ancestor, use:
//h5[ancestor::*[4][self::h1]]
XSLT - based verification:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:copy-of select="//h5[ancestor::*[4][self::h1]]"/>
</xsl:template>
</xsl:stylesheet>
When this transformation is applied on the following XML document:
<t>
<head/>
<body>
<h1>First Main title
<a>
<b>
<c>
<h5 id="id1"/>
<d>
<h5 id="id2"/>
</d>
</c>
</b>
</a>
</h1>
</body>
</t>
the XPath expression is evaluated and the result of the evaluation (the selected h1
elements (in this case just one)) is copied to the output:
<h5 id="id1"/>
If you don't want to count the number of the intermediate levels, butare sure that they don't exceed a certain number (say 7), you can write:
//h1[descendent::*[not(position() > 7)][self::h1]]
This selects any h5
descendent of any h1
, where the "distance" in levels between the h1
and the descendent h5
doesn't exceed 7.
Do note:
An expression like the below -- as suggested in other answers:
//h1//h5
incorrectly selects for the above document:
<h5 id="id1"/>
<h5 id="id2"/>
The second of the two selected h5
elements is at a greater distance than the wanted one from its h1
ancestor.
h5
tags or do you need a specific one in the HTML? If you need a specific one, do you have an ID or CLASS forh5
that'd help you navigate to it, or something specific about the particular one that can be used as a landmark?