Home > Net >  XSLT for recursive XML element
XSLT for recursive XML element

Time:07-20

I am working on an XML standard for swimming programs. I created an XML schema and some example XML files. Since swimming programs often use repetitions (e.g. 4 x 100m Freestyle), I created an XML element <instruction> that can include further instances of itself. It uses the <XS:choice> to either include a <repetition> (e.g 4 x) or direct swimming instructions (100m Freestyle). A <repetition> can then include further repetitions and/or direct swimming instructions.

I am now trying to use XSLT to convert instance1.xml to something like goal.xhtml. While I was able to get the basic XSLT transformation going (e.g. <author>), I am struggling with the recursive nature of the XML Schema and the <instruction>' element. I just can't get my head around how to even start with a solution.

Is there anybody out there who could maybe have a look at the XML file examples and suggest a strategy for the XSLT transformation?

CodePudding user response:

The general strategy in XSLT for dealing with recursive XML structures (i.e. elements which can contain other elements of the same type) is to use template matching. You would create a template which matches the element concerned (e.g. <xsl:template match="instruction">); the template then produces some output, and also uses xsl:apply-templates to process child elements, which (assuming there are child elements of the same type) is effectively a recursive call to the same template.

CodePudding user response:

Reinforcing @ConalTuohy's answer, the standard design pattern for XSLT stylesheets handles recursion without you even needing to think about it. Ask yourself "what do I need to do when I encounter an instruction element?", and the answer will probably be something like "generate a ul element with li elements for its children.". So write a template rule something like

<xsl:template match="instruction">
 <ul>
   <xsl:for-each select"child::node()">
     <li><xsl:apply-templates select="."/></li.
   </xsl:for-each>
 </ul>
</xsl:template>

Note: this answer relates to the general question of "how do I get started". I haven't studied your input and output in any detail.

  • Related