I have a little problem.
A node in my XML may contains and integer, and i have to replace this integer by a string.
Each number match with a string.
For example i have:
Integer – String
1 – TODO
2 – IN PROGRESS
3 – DONE
4 – ERROR
5 – ABORTED
Original XML:
<root>
<status>1</status>
</root>
Converted XML:
<root>
<status>TODO</status>
</root>
So i want replace 1 by “TODO”, 2 by “IN PROGRESS” …
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/root/status">
<root>
<status>
<xsl:variable name="text" select="." />
<xsl:choose>
<xsl:when test="contains($text, '1')">
<xsl:value-of select="'TODO'"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</status></root>
</xsl:template>
</xsl:stylesheet>
I’am asking if there is another way to do that.
There are a number of ways of doing this. Where the translation is from consecutive integers in the range 1 to N, I would use
In other cases where there’s a small number of values I might use template rules:
etc.
In other cases a lookup table makes sense (note that Dimitre’s version with its cumbersome document(”) call is designed for XSLT 1.0 – it’s considerably simpler if you’re using 2.0. When people don’t say what version they are using I generally assume 2.0 and Dimitre generally assumes 1.0.)
I’m increasingly seeing people make the mistake of using contains() when they mean “=”. If you want to test whether the content of a node is “X”, use
$node = "X", notcontains($node, "X").