使用 XPath 查找嵌套元素(相同类型)

Finding nested elements with XPath (same type)

我不知道如何找到相同类型的嵌套元素。通常,如果我有 7 个级别的 headers 并想用 XSLT 将它们转换为 h1–h7 头,如何用 XPath 选择它们——我无法找出比 div/div/div/head 更好的东西,但这似乎真的很笨拙。

这个变换:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="node()|@*">
      <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
    </xsl:template>

    <xsl:template match="div/head">
      <xsl:element name="h{count(ancestor::div)}">
        <xsl:apply-templates select="node()|@*"/>
      </xsl:element>
    </xsl:template>
</xsl:stylesheet>

应用于此 XML 文档时:

<div>
    <head>1</head>
    <div>
        <head>2-1</head>
        <div>
            <head>3-1</head>
        </div>
    </div>
    <div>
        <head>2-2</head>
    </div>
</div>

产生想要的正确结果:

<div>
    <h1>1</h1>
    <div>
        <h2>2-1</h2>
        <div>
            <h3>3-1</h3>
        </div>
    </div>
    <div>
        <h2>2-2</h2>
    </div>
</div>