Search code examples
xsltxslt-2.0xslt-grouping

XSLT apply templates conditioning


I've an issue in apply templates , consider my xml will be like this , enter code here

<card>
   <pre/>
<main>    
  <step1/>
  <step1/>
  <panels>
    <panel/>
    <panel/>
  </panels>
  <step1/>
<main> 
 </card>

Inside main all the step1 will be started with 1. and increment in further step.Now when the panel comes , it should take each panel as a step and it'll start as 3. , 4. next step1 will be 5.

problem is when if i apply templates for step1 in the mainfunc , it's applying for all the step1. so the step1 after the panel also will come in the first place . I want to apply temaplates for the step1 to 3rd step1. then apply panel and then apply the last step1.step1 counts are not always same , they differ.

currently ive something like this ,

<xsl:template match="mainfunc">
    <xsl:apply-templates select="step1"/>
    <xsl:if test="contains($wcType,'P')">
    <xsl:apply-templates select="panels"/>
    </xsl:if>
.....

how to modify to apply the templates in sequence order , also numbering the panel as 3.


Solution

  • This is a bit of a guess, as I am not entirely clear what you want to do, but I think what you could do is this...

    <xsl:apply-templates select="step1|panels[contains($wcType,'P')]"/>
    

    The | symbol is the union operator, and the union of nodes will be selected in document order. So, it will select the first step1, then the panels, then the next step1.

    For example, this XSLT...

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:output method="xml" indent="yes" />
    
        <xsl:variable name="wcType" select="'Pie'" />
    
        <xsl:template match="main">
            <xsl:apply-templates select="step1|panels[contains($wcType,'P')]"/>
        </xsl:template>
    
        <xsl:template match="step1|panel">
            <xsl:copy>
                <xsl:number count="step1|panel" level="any" />
            </xsl:copy>
        </xsl:template>
    </xsl:stylesheet>
    

    When applied to this XML...

    <card>
      <main>    
        <step1/>
        <step1/>
        <panels>
          <panel/>
          <panel/>
        </panels>
        <step1/>
      </main> 
    </card>
    

    The following is output

    <step1>1</step1>
    <step1>2</step1>
      <panel>3</panel>
      <panel>4</panel>
    <step1>5</step1>