Site icon Experiences Unlimited

Setting value of XSL parameter xsl:param in Saxon Java API

In one of my previous posts I showed you how to generate HTML from XML data using XSLT. At times you would need to pass certain parameters to the XSLT and use the value of that parameter in generating your content. In this post we will exactly do that.

This will be our sample XML we will be working with:


This is the HTML we are looking to generate:

Let us look at the XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl=""
    <xsl:output method="html"/>
    <xsl:param name="message" as="xs:string">Hello</xsl:param>
    <xsl:template match="/person">
                    <xsl:value-of select="$message" />, <xsl:value-of select="name" /> from <xsl:value-of select="country" />
                <h4>Programming Languages</h4>
                    <xsl:for-each select="programming-languages/programming-language">
                        <li><xsl:value-of select="." /> </li>


We have the parameter <xsl:param> declared in Line 5 above

Let us look at the Java code where we use Saxon HE library to process the above XSLT and also set the value for the parameter.

public class AppParamDemo {
    public static void main(String[] args) throws SaxonApiException {
        Processor processor = new Processor(false);

        XsltCompiler xsltCompiler = processor.newXsltCompiler();
        InputStream xsltStream = ClassLoader.getSystemResourceAsStream("sample-xslt3.xsl");
        xsltCompiler.setParameter(new QName("message"), new XdmAtomicValue("Good Morning"));
        XsltExecutable xsltExecutable = xsltCompiler.compile(new StreamSource(xsltStream));
        Xslt30Transformer xsltTransformer30 = xsltExecutable.load30();

        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
        Serializer byteArrayOutput = xsltTransformer30.newSerializer(arrayOutputStream);
        byteArrayOutput.setOutputProperty(Serializer.Property.INDENT, "yes");
        byteArrayOutput.setOutputProperty(Serializer.Property.METHOD, "html");
        byteArrayOutput.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes");

        StreamSource streamSource = new StreamSource(ClassLoader.getSystemResourceAsStream("sample-xml3.xml"));
        xsltTransformer30.transform(streamSource, byteArrayOutput);

In the above code at Line 7 we set the value for the parameter message.

The working code can be found at the Github repository:

Exit mobile version