计算xml-tree的最大深度

Ili*_*sov 0 xml xslt xpath

用于计算xml缩进深度的最简单的xpath 2.0是什么?我的变体还不聪明:

<xsl:param name="maxdepth" select="number(substring(concat(
'16'[count(current()/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*)>0],
'15'[count(current()/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*)>0],
'14'[count(current()/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*)>0],
'13'[count(current()/*/*/*/*/*/*/*/*/*/*/*/*/*/*)>0],
'12'[count(current()/*/*/*/*/*/*/*/*/*/*/*/*/*)>0],
'11'[count(current()/*/*/*/*/*/*/*/*/*/*/*/*)>0],
'10'[count(current()/*/*/*/*/*/*/*/*/*/*)>0],
'09'[count(current()/*/*/*/*/*/*/*/*/*)>0],
'08'[count(current()/*/*/*/*/*/*/*/*)>0],
'07'[count(current()/*/*/*/*/*/*/*)>0],
'06'[count(current()/*/*/*/*/*/*)>0],
'05'[count(current()/*/*/*/*/*)>0],
'04'[count(current()/*/*/*/*)>0],
'03'[count(current()/*/*/*)>0],
'02'[count(current()/*/*)>0],
'01'[count(current()/*)>0])
,1,2)
)"/>
Run Code Online (Sandbox Code Playgroud)

Dim*_*hev 5

用途:

max(//node()[not(node())]/count(ancestor-or-self::node()))
Run Code Online (Sandbox Code Playgroud)

这将生成XML文档中叶节点的所有深度的最大深度,包括/级别1 的文档节点().

这是一个完整的例子:

<xsl:stylesheet version="2.0"   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>

 <xsl:template match="/">
     <xsl:sequence select=
      "max(//node()[not(node())]/count(ancestor-or-self::node()))"/>
 </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

将此转换应用于以下XML文档时:

<root>
   <x>This is:</x>
   <a>
      <b>
         <c>hello</c>
      </b>
   </a>
   <a>
      <b>
         <c1>world</c1>
      </b>
   </a>
   <a>
      <b>!</b>
   </a>
   <y>The End</y>
</root>
Run Code Online (Sandbox Code Playgroud)

产生了想要的正确结果:

6
Run Code Online (Sandbox Code Playgroud)

更新:

如果需要任何元素的最大深度,请使用几乎相同的XPath表达式:

max(//*[not(*)]/count(ancestor-or-self::*))
Run Code Online (Sandbox Code Playgroud)