Search code examples
xmltemplatesxsltapply-templates

Rendering different templates for the same XML element, at same level


XML:

<Root>
  <Elements>
    <Element>el1</Element>
    <Element>el2</Element>
   </Elements>

  <Elements>
    <Element>el1</Element>
    <Element>el2</Element>
   </Elements>
</Root>

Trying to generate to apply two different templates for the same element.

Main template:

<xsl:stylesheet version="1.0">
      <xsl:template match="/Root">
           At root level
             <xsl:apply-templates select="Elements">

             <h1>Render something more</h1>

             <xsl:apply-templates select="Elements" mode="1:Custom">
        </xsl:template>


    <!-- This doesn't render though it is called above-->
      <xsl:template match="Elements"> 
      render something here
      </xsl:template>

    <!-- This renders twice -->
      <xsl:template match="Elements" mode="1:Custom">
      render something else here
      </xsl:template>
</xsl:stylesheet>

If I add mode to the first template, both don't render.

Also tried:

 <xsl:apply-templates select="Elements" mode="1:Custom" />

with the different template to apply as:

<xsl:apply-templates select="Elements" mode="Different" />

Only one of the two(the first one which has the mode specified is rendered). i.e

<xsl:template match="Elements">
</xsl:template>

doesn't render

or <xsl:template match="Elements" mode="Different" />renders twice.

How should I fix this? Everywhere I researched, it suggests to put a priority on the mode. Must be something simple since so many programmers use it?


Solution

  • <?xml version="1.0"?>
    
    <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
          <xsl:template match="/Root">
               At root level
                 <xsl:apply-templates select="Elements"/>
    
                 <h1>After first template</h1>
    
                 <xsl:apply-templates select="Elements" mode="Custom"/>
            </xsl:template>
    
          <xsl:template match="Elements">
          <p>First template</p> 
              <xsl:apply-templates select="Element"/>
          </xsl:template>
    
          <xsl:template match="Elements" mode="Custom">
             <p>Second template      </p>
          </xsl:template>
          </xsl:stylesheet>