How do I pass an input parameter to an XSLT stylesheet? I'm using xsltproc, and I'd like to use --stringparam <param> <value>
as argument, but I don't know how to access the parameter inside the XSLT. Can someone give an example? Thanks in advance.
How to give input parameter to an xslt file?
In XSLT any global parameter (xsl:param
that is a child of the top element of the XSLT stylesheet) can have its value specified externally, by the initiator of the transformation.
The way this setting of external parameters is done is implementation dependent and differs from one XSLT processor to another -- read the documentation of the specific XSLT processor you are using.
Here is a small example:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pDeletePos" select="3"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="num">
<xsl:if test="not(position() = $pDeletePos)">
<xsl:copy-of select="."/>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Here, the global parameter named pDeletePos
the position of the num
element that must be deleted.
There is also a default value
(3), specified for this parameter. This value will be used if the initiator of the transformation doesn't specify the pDeletePos
parameter.
When the above transformation is applied on this XML document:
<nums>
<num>01</num>
<num>02</num>
<num>03</num>
<num>04</num>
<num>05</num>
<num>06</num>
<num>07</num>
<num>08</num>
<num>09</num>
<num>10</num>
</nums>
and if the value of the pDeletePos
is externally specified as 5
, then the transformation produces the following result:
<nums>
<num>01</num>
<num>02</num>
<num>03</num>
<num>04</num>
<num>06</num>
<num>07</num>
<num>08</num>
<num>09</num>
<num>10</num>
</nums>
As for setting the parameter externally, here is how this is done in C#, when initiating the XslCompiledTransform XSLT processor:
http://msdn.microsoft.com/en-us/library/system.xml.xsl.xsltargumentlist.addparam.aspx
This is one I am using. The default value part is optional. You must have a
<xsl:param name="yourParamname"/>
.
<?xml version="1.0"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- default value -->
<xsl:variable name="defaultDeploymentMode">
<xsl:text>test</xsl:text>
</xsl:variable>
<xsl:param name="deploymentMode" select="$defaultDeploymentMode"></xsl:param>
<xsl:template match="/">
<data><xsl:value-of select="$deploymentMode"/>
</data>
</xsl:template>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With