Difficulty: ★☆☆ (easy)
Keywords: sectX, section, section to sectX

Problem

You need to transform every sectX element into a section element.

Solution

This problem is solved through the following XSLT stylesheet:

Example 3.11. Transforms every sectX Element into a section Element
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
  xmlns:d="http://docbook.org/ns/docbook"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">
  
  <xsl:import href="copy.xsl"/>
  
  <xsl:template match="d:section">
    <xsl:variable name="level" select="count(ancestor::*)"/>
    <xsl:element name="sect{$level}" namespace="http://docbook.org/ns/docbook">
      <xsl:copy-of select="@*"/>
      <xsl:apply-templates/>
    </xsl:element>
  </xsl:template>
  
</xsl:stylesheet>

Discussion

The above stylesheet calculates the section level with the ancestor axis, because the amount of elements is directly correlated with the level of the corresponding section. With an attribute value template it is inserted in the name attribute.

There is one caveat: The stylesheet does not check if the limit is reached. Currently (with version 5.1), DocBook supports levels up to 5. If you nest your section elements too deep, you can end up with, let's say, sect8 which is not allowed in DocBook. To avoid making mistakes, it is better to check the level:

Example 3.12. Error Checking of Section Levels
<xsl:template match="d:section">
  <xsl:variable name="level" select="count(ancestor::*)"/>
  <xsl:choose>
    <xsl:when test="$level &lt;= 5">
      <xsl:element name="sect{$level}"
          namespace="http://docbook.org/ns/docbook">
        <xsl:copy-of select="@*"/>
        <xsl:apply-templates/>
      </xsl:element>
    </xsl:when>
    <xsl:otherwise>
      <xsl:message>ERROR: section <xsl:value-of
          select="normalize-space(d:title)"/> to deep</xsl:message>
      <!-- What to do if the section is too deeply nested? -->
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

Amend the stylesheet when the section is too deeply nested (see above comment). You could avoid the section level (which is a bad idea) but it's better to rework the source document.

If you want, you can stop the transformation if the section level is too high. Change the xsl:message as follows:

<xsl:message terminate="yes">...

Project@GitHubIssue#8