开发者

How to change headers level by XSLT based on depth in XML

My XSL-file:

        ...
        <div>

          <xsl:choose>
            <xsl:when test="count(ancestor::node()) = 1">
              <h2>
            </xsl:when>
            <xsl:when test="count(ancestor::node()) = 2">
              <h3>
            </xsl:when>
          </xsl:choose> 

            <xsl:attribute name="id">
              <xsl:value-of select="@id" />
            </xsl:attribute>
            <xsl:copy-of select="title/node()"/>

          <xsl:choose>
            <xsl:when test="count(ancestor::node()) = 1">
              </h2>
            </xsl:when>
            <xsl:when test="count(ancestor::node()) = 2">
              </h3>
            </xsl:when&开发者_StackOverflowgt;
          </xsl:choose> 

        </div>

I know that it is not allowed to split tags h2.../h2, h3.../h3 like this.

But how to do this correctly?


You could do this with a recursive template and generate the heading element dynamically.

For example, this input XML:

<input>
  <level id="1">
    <title>first</title>
    <level id="2">
      <title>second</title>
      <level id="3">
        <title>third</title>
      </level>
    </level>
  </level>
</input>

processed by this XSLT:

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

<xsl:template match="level">
  <xsl:variable name="level" select="count(ancestor-or-self::level) + 1"/>

  <xsl:element name="h{$level}">
    <xsl:attribute name="id">
      <xsl:value-of select="@id"/>
    </xsl:attribute>
    <xsl:copy-of select="title/node()"/>
  </xsl:element>

  <xsl:apply-templates select="level"/>
</xsl:template>
</xsl:stylesheet>

gives the following HTML:

<h2 id="1">first</h2>
<h3 id="2">second</h3>
<h4 id="3">third</h4>


You could use

<xsl:template match="/div">
  <h1><xsl:apply-templates/></h1>
</xsl:template>

<xsl:template match="/*/div">
  <h2><xsl:apply-templates/></h2>
</xsl:template>

<xsl:template match="/*/*/div">
  <h3><xsl:apply-templates/></h3>
</xsl:template>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜