2011-04-29 74 views
0

章节和节的高度可以分别计算。仅使用匹配模板。 这是输入:目录的高度:查找节点的最大深度

<?xml version='1.0' encoding='UTF-8'?> 
<!DOCTYPE book SYSTEM "book.dtd"> 
<book title="Definitive XML Schema"> 
    <author first="Priscilla" last="Walmsley"/> 
    <chapter title="A"> 
     <section title="d"/> 
     <section title="g"> 
      <section title="s"/> 
      <section title="t"/> 
     </section> 
     <section title="e"> 
      <section title="f"/> 
     </section> 
    </chapter> 
    <chapter title="B"> 
     <section title="n"/> 
     <section title="c"> 
      <section title="a"/> 
      <section title="m"/> 
     </section> 
    </chapter> 
</book> 

的出放为:

3 

如果要计算section节点的最大深度是section节点

+1

您是否意味着您想获得树的最大深度? – Erica 2011-04-29 06:00:00

+0

@Erica:是的,这是正确的.. – ZAWD 2011-04-29 07:20:29

回答

1

的最大深度,您可以使用以下XSLT:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="1.0"> 

    <xsl:output method="text"/> 

    <xsl:template match="book"> 
     <xsl:for-each select="//section"> 
      <xsl:sort select="count(ancestor::node())" 
       data-type="number" order="descending"/> 
      <xsl:if test="position() = 1"> 
       <xsl:value-of select="count(ancestor::node()) - 1"/> 
      </xsl:if> 
     </xsl:for-each> 
    </xsl:template> 

</xsl:stylesheet> 

w给定示例XML作为输入,将产生以下输出:

3