Reputation: 447
I am new to xslt and trying to convert below xml using a xslt. I am trying to modify 2 fields (one is number and another of string type)using below xslt.
<items>
<item>
<item_id>27989498</item_id>
<service>Test Fee1</service>
<rate>350</rate>
<quantity>1</quantity>
<tax_rate>0</tax_rate>
<item_date>2010-11-17-05:00</item_date>
</item>
</items>
XSLT :
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="rate[ . > 0 ]">
<xsl:copy>100</xsl:copy>
</xsl:template>
<xsl:template match="service[ . &eq; 'Test Fee1' ]">
<xsl:copy>T1</xsl:copy>
</xsl:template>
Output :
<items>
<item>
<item_id>27989498</item_id>
<service>Test Fee1</service>
<rate>100</rate>
<quantity>1</quantity>
<tax_rate>0</tax_rate>
<item_date>2010-11-17-05:00</item_date>
</item>
</items>
Above XSLT is replacing rate field correctly but for string field "service" it's not replacing the intended value. How can I compare and replace string in xslt as "eq" method is not working.
Is it possible to select the replace value from a list of values instead of hard coding? Example : Test Fee1 = T1 , Test Fee2 = T2 , Test Fee3 =T3 etc.
Update :
In the request xml service tag will not have a value from series instead it will be a random value, which needs to be replaced with some keys like state names of a country should be replaced by state code without taking case sensitivity into consideration.
Example : New York = NY or new yoRk = NY, Arizona = AR etc.
Upvotes: 0
Views: 1384
Reputation: 1458
A very simplistic approach in XSLT 1.0:
<xsl:template match="service[starts-with(., 'Test Fee')
and number(substring-after(., 'Test Fee')) > 0]">
<service>
<xsl:text>T</xsl:text>
<xsl:value-of select="substring-after(., 'Test Fee')"/>
</service>
</xsl:template>
This could be further refined to your requirements, depending on which values you actually allow for <service>.
Upvotes: 1
Reputation: 167401
Assuming an XSLT 1.0 (or later) processor you simply use match="service[. = 'Test Fee1' ]"
. With an XSLT 2.0 processor you could also use match="service[. eq 'Test Fee1' ]"
. Also match="rate[ . > 0 ]"
can be simplified to match="rate[ . > 0 ]"
.
Upvotes: 1