Question

I am trying to traverse Docbook section nodes. Their structure are as follows:

<sect1>
   <sect2>
      <sect3>
         <sect4>
            <sect5>
            </sect5>
         </sect4>
      </sect3>
   </sect2>
</sect1>

So sect1 only have sect2 inside, sect2 will only have sect3 inside, and so on. We can also have multiple sub nodes within a node; for instance multiple sect2 within a sect1.

Programatically I would iterate through them recursively using a counter for keeping track of which section the loop is at.

This time I have to use XSLT and to loop through it. Thus is there an equivalent way, or better way of doing this in XSLT?

Edit: I already have similar code as suggested by Willie, where I specify every sect node (sect1 to sect5). I am looking for solution where it loops determining the sect node by itself, and I won't have to repeat code. I am aware that Docbook specs only allows up to 5 nested nodes.

Was it helpful?

Solution

If you are doing the same processing to all sect{x} nodes, regardles of {x}, as you say in one of the comments, then the following is sufficient:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match=
     "sect1|sect2|sect3|sect4|sect5">
      <!-- Some processing here -->
      <xsl:apply-templates/>
    </xsl:template>
</xsl:stylesheet>

If you really need to process in the same way many more elements having different names of the form "sect"{x} (let's say x is in the range [1, 100]), then the following can be used:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match=
     "*[starts-with(name(), 'sect')
      and
        substring-after(name(), 'sect') >= 1
      and
        not(substring-after(name(), 'sect') > 101)
       ]">
      <!-- Some processing here -->
      <xsl:apply-templates/>
    </xsl:template>
</xsl:stylesheet>

OTHER TIPS

<xsl:template match="sect1">
    <!-- Do stuff -->
    <xsl:apply-templates />
</xsl:template>

<xsl:template match="sect2">
    <!-- Do stuff -->
    <xsl:apply-templates />
</xsl:template>

<xsl:template match="sect3">
    <!-- Do stuff -->
    <xsl:apply-templates />
</xsl:template>

<xsl:template match="sect4">
    <!-- Do stuff -->
    <xsl:apply-templates />
</xsl:template>

<xsl:template match="sect5">
    <!-- Do stuff -->
    <xsl:apply-templates />
</xsl:template>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top