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

我是研究僧i 提交于 2019-11-28 11:37:43

问题



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

<org.olat.course.nodes.STCourseNode>                    0
   <ident>81473730700165</ident>                        1
   <type>st</type>
   <shortTitle>General Information</shortTitle>
       <moduleConfiguration>                            2
          <config>                                      3
             <entry>                                    4
                <string>allowRelativeLinks</string>     5           <---
                <string>false</string>
             </entry>
             <entry>
                <string>file</string>
                <string>/kgalgemeneinformatie.html</string>          
             </entry>
             <entry>
                <string>configversion</string>
                <int>3</int>
             </entry>
             <entry>
                <string>display</string>
                <string>file</string>
             </entry>
          </config>
       </moduleConfiguration>
    </org.olat.course.nodes.STCourseNode>



Note: I use php, xpath

Other possibilities are also welcome :)

Kind regards

Dieter Verbeemen


回答1:


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


来源:https://stackoverflow.com/questions/9890097/how-do-you-find-the-deepest-node-steps-xpath-php-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!