2012-03-27 77 views
0


问候你怎么找到最深的节点(步) - Xpath的 - PHP - XML -

你怎么找到最深的节点? 所以在这个例子中,字符串将是最深的节点:

,而我要的是

<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> 



注的结果:我使用PHP,的XPath其他可能性也欢迎:)

亲切的问候

迪特Verbeemen

回答

1

在XPath 2.0你可以写一个XPath表达式,我认为,作为max(descendant::*[not(*)]/count(ancestor::*))。在XPath 1.0,你可以找到XSLT作为

<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> 

的节点作为宿主语言。如果你使用PHP的“主机”语言的XPath你也许可以写一个循环类似的东西在descendant::*[not(*)],元素不有任何子元素,并为每个元素计算count(ancestor::*)并存储最大值。

[编辑]下面是一些企图在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