XSLT templates dynamically adding "wrapper" elements

50 Views Asked by At

I am blessed to work with the SAP B1 Integration Framework, XSLT 1.0 but supports EXSLT at least. So we have this input XML. Result of JDBC SQL...

<xsl:apply-templates select="//jdbc:ResultSet[1]/Row" mode="payment"/>
<xsl:apply-templates select="//jdbc:ResultSet[2]/Row" mode="positions"/>

<xsl:template match="jdbc:Row" mode="payment">
    <Documents> 
        <row>           
            <xsl:apply-templates mode="fields"/>        
        <row>               
    </Documents>
</xsl:template>
<xsl:template match="jdbc:Row" mode="positions">
    <Document_Lines>
        <row>
            <xsl:apply-templates mode="fields"/>        
        </row>              
    </Document_Lines>
</xsl:template>

<xsl:template match="*" mode="fields">
    ... do stuff ...
</xsl:template>             

The only reason I have these payment and positions modes is this static wrapper element, Documents/rows, Document_Lines/rows

How do I get rid of this duplication and somehow pass the wrapper with exslt:node-set ? Or some other way?

1

There are 1 best solutions below

1
Daniel Haley On

You could have a single template matching jbdc:Row that has an xsl:param where you pass the element name...

<!-- xsl:apply-templates can't be at the same level as xsl:template, so I'm assuming these are located in an unspecified xsl:template somewhere.-->
<xsl:apply-templates select="//jdbc:ResultSet[1]/Row">
    <xsl:with-param name="base_elem_name" select="'Documents'"/>
</xsl:apply-templates>
<xsl:apply-templates select="//jdbc:ResultSet[2]/Row">
    <xsl:with-param name="base_elem_name" select="'Document_Lines'"/>
</xsl:apply-templates>

<xsl:template match="jdbc:Row">
    <xsl:param name="base_elem_name"/>
    <xsl:element name="{$base_elem_name}">
        <row>           
            <xsl:apply-templates mode="fields"/>        
        </row>
    </xsl:element>
</xsl:template>

<xsl:template match="*" mode="fields">
    ... do stuff ...
</xsl:template>