(Q22) Find the maximum depth of the document named "partlist.xml."

NAMESPACE xsd = "http://www.w3.org/2000/10/XMLSchema-datatypes"

FUNCTION depth(ELEMENT $e) RETURNS xsd:integer
{
   -- An empty element has depth 1
   -- Otherwise, add 1 to max depth of children
   IF empty($e/*) THEN 1
   ELSE max(depth($e/*)) + 1
}

depth(document("partlist.xml"))

XSLT equivalent to (Q22)

<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template name="depth">
    <xsl:param name="node"/>
    <xsl:param name="level" select="1"/>
    <xsl:choose>
      <xsl:when test="not($node/*)">
        <xsl:value-of select="$level"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:call-template name="depth">
          <xsl:with-param name="level" select="$level + 1"/>
          <xsl:with-param name="node" select="$node/*"/>
        </xsl:call-template>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
  <xsl:template match="/">
    <xsl:call-template name="depth">
      <xsl:with-param name="node" select="document('partlist.xml')"/>
    </xsl:call-template>
  </xsl:template>
</xsl:transform>
  • The XSLT solution similarily uses a recursive named template to compute the same value.
<<<  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15    >>>