Erkan
Erkan

Reputation: 1

How can I write recursive XSLT code

I have dynamic XML data and I use following xslt code to generate html. XML structure contains chapter, subchapter, checklist and summary nodes.

My code works but, all the time subchapter's content added before checklist. If chapter involves checklist,subchapter nodes (first checklist), subchapter content created first.

How can I correct this or how can I rewrite the following code as recursive?

  <xsl:template match="chapter">
    <xsl:apply-templates select="chapter"/>
  </xsl:template>

  <xsl:template match="chapter">    
    <table>
      <tr>
        <td>
          <h2>
            <xsl:value-of select="@name"/>
          </h2>
        </td>
      </tr>
      <xsl:apply-templates select="subchapter"/>
      <xsl:apply-templates select="checklist"/>
    </table>
  </xsl:template>



  <xsl:template match="subchapter">

      <tr>
        <td>
          <h3>
            <xsl:attribute name="name">
              <xsl:value-of select="@value"/>
            </xsl:attribute>
            <xsl:value-of select="@name"/>
          </h3>
        </td>
      </tr>

      <xsl:apply-templates select="subchapter"/>
      <xsl:apply-templates select="checklist"/>

  </xsl:template>


  <xsl:template match="checklist">    
      <tr>
        <td>
          <h4>
            <xsl:attribute name="name">
              <xsl:value-of select="@value"/>
            </xsl:attribute>

            <xsl:value-of select="@name"/>

          </h4>
        </td>
      </tr>

      <xsl:apply-templates select="summary"/>

  </xsl:template>

  <xsl:template match="summary">    
      <tr>
        <td>
          <xsl:copy-of select="*"/>
        </td>
      </tr>    
  </xsl:template>

Upvotes: 0

Views: 86

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117073

I am guessing (without seeing the input and the expected output, I can only guess), that instead of:

<xsl:apply-templates select="subchapter"/>
<xsl:apply-templates select="checklist"/>

you want :

<xsl:apply-templates select="subchapter | checklist"/>

If chapter contains only subchapter and checklist you can shorten that to:

<xsl:apply-templates/>

Upvotes: 2

Related Questions