I’m using XSLT to transform from one format of XML into another but I also need to do some value substitutions at the same time if possible. Can someone provide a solution to change a large number of values; e.g. “AppName” should be changed to “1”, “AppNameTwo” to “2” and I’d ideally like to do this via some type of look-up lists within the XSLT:
<Application>
<oldvalue="AppName" replacewith="1">
<oldvalue="AppNameTwo" replacewith="2">
</Application>
<ResponseOne>
<oldvalue="True" replacewith="Okay">
<oldvalue="False" replacewith="Error">
</ResponseOne>
The only way I can currently think of doing this is instead via a number of many nested replaces?
Input
<Message>
<Header>
<Application>AppName</Application>
<ResponseOne>True</ResponseOne>
...
</Header>
</Message>
XSLT so far
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0">
<xsl:template match="/">
<n1:Message>
<Header>
<Application><xsl:value-of select="//Message/Organisation/Application/Name"/> </Application>
<Response><xsl:value-of select="//Message/Organisation/Application/ResponseOne"/> </Response>
...
</Header>
</n1:Message>
Required Output
<?xml version="1.0" encoding="utf-8"?>
<n1:Message>
<Header>
<Application>1</Application>
<Response>Error</Response>
...
</Header>
</n1:Message>
Intending to run this XSLT within Visual Studio 2010.
This simple transformation (only a single template overriding the identity rule and no need for extension functions), allows the use of huge number of replacement rules, without the need to change the code at all. Another alternative is to specify the value of the global parameter
$pRepsoutside of the transformation — then this code can be even slightly simplified:When applied on the provided XML document:
the wanted, correct result is produced:
Explanation:
The identity rule (template) copies every node “as-is”.
The replacement rules are coded as a sequence of
elemelements that are children of the global paramertepReps. The structure and meaning of everyelemelement should be self-explanatory.There is a single template overriding the identity rule, that matches any text node. Within this template a possible new value is calculated as defined by the variable
$vNewVal. This is either the empty node-set (in case the parent name of the current node and the string value of the current node are not matced by anyreplace/thisvalue from the$pReps. Or, if matched, this is thewithsibling of the matchingreplace/thisvalue from the$pReps. Finally, either$vNewVal(if not empty) or the current node are copied.