How do you find the deepest node (steps) - Xpath - php - xml -

前端 未结 1 1899
忘掉有多难
忘掉有多难 2020-12-22 09:38


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

相关标签:
1条回答
  • 2020-12-22 10:13

    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
    
    0 讨论(0)
提交回复
热议问题