How to loop using XSLT through hierarchical nodes?

I am trying to go through the nodes of the Docbook section. Their structure is as follows:

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

So, sect1 has only a sect inside, sect2 will only have a section inside, etc. We can also have several sub-settings within node; for example, multiple sect2 within sect1.

Programmatically, I would iterate over them recursively, using a counter to track which section the loop is in.

This time I have to use XSLT and skip it. So is there an equivalent way, or a better way to do this in XSLT?

Edit: I already have a similar code suggested by Willy, where I point to every sect node (sect1 - sect5). I am looking for a solution where it will define the node section by itself, and I won’t have to repeat the code. I know that Docbook specifications only allow up to 5 nested nodes.

+3
source share
2 answers

If you do the same processing on all sect {x} nodes, the {x} aspects, as you say in one of the comments, then enough :

<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 as many other elements that have different names of the form "sect" {x} (let x be in the range [1, 100]), then you can use the following:

<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>
+4
source
<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>
0
source

Source: https://habr.com/ru/post/1704941/


All Articles