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

吃可爱长大的小学妹 提交于 2019-11-29 18:38:24

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