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

前端 未结 1 1905
忘掉有多难
忘掉有多难 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

    
      
        
        
          
        
      
    
    

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