Reputation: 45
I am very new to xslt and need some help with some string manipulation. I am trying to work on a xslt where i want to replace all occurrences of special character '&' with 'and' in xml. One of the few things i have tried
<xsl:template match="Model">
<Model>
<xsl:value-of select="replace(//P1/P2/Vehicles/Vehicle/Model, '&','and')"/>
</Model>
</xsl:template>
it is working fine if there is only one vehicle, however if there are multiple vehicles it is not working.
The xml:
<P1>
<someNode>
<P2>
<Vehicles>
<Vehicle>
<Id>1</Id>
<Make>My car</Make>
<Model>my model & something</Model>
</Vehicle>
<Vehicle>
<Id>2</Id>
<Make>My car2</Make>
<Model>my model2</Model>
</Vehicle>
</Vehicles>
</P2>
<P1>
Any help is highly appreciated. Thanks!
Upvotes: 2
Views: 2494
Reputation: 52858
If you want to replace all occurrences of &
, another option is to use an xsl:character-map...
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" use-character-maps="cmap"/>
<xsl:strip-space elements="*"/>
<xsl:character-map name="cmap">
<xsl:output-character character="&" string="and"/>
</xsl:character-map>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Working fiddle: http://xsltfiddle.liberty-development.net/93wniTP
Upvotes: 0
Reputation: 22167
The provided XML is not well-formed. I had to fix it.
The XSLT is using Identity Transform pattern.
XML
<P1>
<someNode/>
<P2>
<Vehicles>
<Vehicle>
<Id>1</Id>
<Make>My car</Make>
<Model>my model & something</Model>
</Vehicle>
<Vehicle>
<Id>2</Id>
<Make>My car2</Make>
<Model>dog & pony</Model>
</Vehicle>
</Vehicles>
</P2>
</P1>
XSLT
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Model">
<xsl:copy>
<xsl:value-of select="replace(., '&','and')"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Upvotes: 1