Carsten 的测试用例有效(稍作调整,您需要用 / 终止 xsl:value-of),但始终使用 <h2> 作为标题。如果你想根据标题的嵌套级别使用不同的标题元素,那么你还需要一些东西:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates />
</body>
</html>
</xsl:template>
<xsl:template match="title">
<xsl:choose>
<xsl:when test="count(ancestor::section) = 1">
<h1><xsl:value-of select="." /></h1>
</xsl:when>
<xsl:when test="count(ancestor::section) = 2">
<h2><xsl:value-of select="." /></h2>
</xsl:when>
<xsl:otherwise>
<h3><xsl:value-of select="." /></h3>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="para">
<p><xsl:value-of select="." /></p>
</xsl:template>
</xsl:stylesheet>
XPath 函数count(ancestor::section) 将返回作为当前元素父元素的所有<section> 元素的计数。在示例中,我使用了<h1> 和<h2> 用于最外层的两个级别,<h3> 用于更深的嵌套,当然您可以在离题时使用其他差异化。
甚至可以使用以下表达式动态生成航向后的数字:
<xsl:template match="title">
<xsl:variable name="heading">h<xsl:value-of select="count(ancestor::section)" /></xsl:variable>
<xsl:element name="{$heading}">
<xsl:value-of select="." />
</xsl:element>
</xsl:template>
其中的xsl:variable 部分创建了一个值为h + 嵌套级别的变量。然后该变量可用作xsl:element 元素的参数,允许您动态定义要创建的元素的名称。
跟进:如果您只想按照建议使用 h1-h6,您可以这样做:
<xsl:template match="title">
<xsl:variable name="hierarchy" select="count(ancestor::section)"/>
<xsl:variable name="heading">h<xsl:value-of select="$hierarchy" /></xsl:variable>
<xsl:choose>
<xsl:when test="$hierarchy > 6">
<h6 class="{$heading}"><xsl:value-of select="." /></h6>
</xsl:when>
<xsl:otherwise>
<xsl:element name="{$heading}">
<xsl:value-of select="." />
</xsl:element>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
此表达式使用<h6 class="h..."> 表示嵌套深度超过 6 的任何内容。它使用<h1> 到<h6> 表示所有其他层次结构级别。