Parametrize your xml documents using XSLT and java

Recently, i used XSLT to parametrize an XML document. XSLT transformations are used to transform a Source document to a Destination document using a style sheet (XSL). To solve this problem the the source document is empty and the style sheet is the document itself with placeholders.

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:param name="param1" select="'defaultval1'" />
	<xsl:param name="param2" select="'defaultval2'" />
	<xsl:template match="/">
		<people>
			<person age="{$param1}"><xsl:value-of select="$param2" /></person>
		</people>
	</xsl:template>
</xsl:stylesheet>
1
2
3
4
5
6
7
8
9
10
File xsltFile = new File("template.xsl");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document emptySourceDoc = builder.newDocument();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer xsltTransformer = transformerFactory.newTransformer(new StreamSource(xsltFile));
xsltTransformer.setParameter("param1", "value1");
xsltTransformer.setParameter("param2", "value2");
StreamResult result = new StreamResult(System.out);
xsltTransformer.transform(new DOMSource(emptySourceDoc), result);

Cant we have the placeholders in the XML source document? I am unaware of any straightforward way to substitute placeholders in a Source document using style sheets and passing parameters. It also seems using a DOMSource for the xslt file seems to be an issue. More on that here.

One more thing is you dont need to escape XML characters before passing the String as a parameter to the XSLT transformer. Try a simple experiment, disable-output-escaping=”yes” to xsl:value-of tag.

1
<xsl:value-of select="$param2" disable-output-escaping="yes" />

Now, if you pass any of XML’s escape characters { “, ‘, <, >, &} in the string, it shouldn’t escape them and your xml file will be incorrectly generated. By default disable-output-escaping is set to “no” so escaping works fine.