2

I would seek this your guidance for doubt in XSLT. In my current project there is a requirement to create many XSLT files. In these transformations, there are few common steps performed; for.eg. changing uppercase of an element value from input xml. I'm currently using the below code in an XSLT, so if there are 50 XSLT being created then this code will be duplicated.

<xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" />
            <xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" /> 
            <xsl:message>UPPERCASE is <xsl:value-of select="translate($MsgType, $smallcase, $uppercase)" /></xsl:message>  

Requesting your advice on how to avoid code duplication. Can I create a common XML file such as utility and declare the variables uppercase and smallcase and shall I call these variables inside the xslt. Similar to other prog. lang like java where I can declare a common function globally and use it in different classes. Basically I would like to know whether it is possible to declare globally and use it in all the xslt.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Ajai Singh
  • 33
  • 2
  • 6

2 Answers2

2

I would use <include/> to include the XSLT file with all your global variables defined. See also http://www.w3.org/TR/xslt#element-include

Put all your variables into the file "my_global_variables.xsl":

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:variable name="myVariable" select="'xyz'"/>

<!-- more variables to add -->

</xsl:stylesheet>

Your main stylesheet looks like this then, including the "my_global_variables.xsl":

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:include href="my_global_variables.xsl"/>

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

There is also the <import> element with which you can import stylesheets. An imported style sheet has lower precedence than the importing style sheet though - so in your case I would use <include>.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Peter
  • 1,786
  • 4
  • 21
  • 40
1

Requesting your advice on how to avoid code duplication. Can I create a common XML file such as utility and declare the variables uppercase and smallcase and shall I call these variables inside the xslt.

<xsl:import> and <xsl:include> are the two XSLT instructions especially designed for this task.

Global variables (children of an xsl:stylesheet element) in a stylesheet module are accessible in the stylesheet that includes this stylesheet. The rules with importing are a little bit more complicating, but if there are no naming conflicts between global variables from imported stylesheets, they are all accessible from the importing stylesheet.

Finally, I recommend not to use www.w3schools.com -- see why at: http://www.w3fools.com

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431