Greetings
How do you find the deepest node? So for this example, String would be the deepest node:
and the result that I want is 5
With XPath 2.0 you could write a single XPath expression I think, as max(descendant::*[not(*)]/count(ancestor::*))
. With XPath 1.0 you could find the node with XSLT as the host language as in
<xsl:template match="/">
<xsl:for-each select="descendant::*[not(*)]">
<xsl:sort select="count(ancestor::*)" data-type="number" order="descending"/>
<xsl:if test="position() = 1">
<xsl:value-of select="count(ancestor::*)"/>
</xsl:if>
</xsl:for-each>
</xsl:template>
If you use PHP as the "host" language for XPath you can probably write something similar with a loop over descendant::*[not(*)]
, the elements not having any child elements, and computing count(ancestor::*)
for each of them and storing the maximum value.
[edit] Here is some attempt at PHP:
$xpath = new DOMXPath($doc);
$leafElements = $xpath->query("descendant::*[not(*)]");
$max = 0;
foreach ($leafElements as $el) {
$count = $xpath->evaluate("count(ancestor::*)", $el);
if ($count > $max) {
$max = $count;
}
}
// now use $max here