I have a xsl template which can replace some xml values.
Now I want these values to be dynamically generated by my code.
Transformer trans = TransformerFactory.newInstance().newTransformer(new StreamSource(new File("foo.xsl"));
trans.transform(new StreamSource(new File("foo.xml"), new StreamResult(new File("output.xml")));
How can I acchive eg replacing the name ONLY where id=1? And moreover provide that id dynamically by javacode, not hardcoded?
<?xml version="1.0"?>
<my:accounts xmlns:my="http://myns">
<my:account>
<my:name>alex</my:name>
<my:id>1</my:id>
</my:account>
<my:account>
<my:name>Fiona</my:name>
<my:id>2</my:id>
</my:account>
</my:accounts>
This replaces all names:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="http://myns">
<xsl:param name="propertyName" select="'alex'"/>
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[local-name()='account']/*[local-name()='name']/text()[.='{$propertyName}']">
<xsl:text>johndoe</xsl:text>
</xsl:template>
</xsl:stylesheet>
This transformation:
when applied on the provided XML document:
produces the wanted, correct result:
Explanation:
Use of a global-scope
<xsl:param>. Although a default value is set, this is overriden by the value specified by the invoker of the transformation.Do note that the question how to specify the value of an external parameter to the transformation has different answers for differen xslt processors (vendors). You need to read the documentation of the specific XSLT processor you are using to get this answer for your particular case.