Reputation: 11
i am working to get the nodes of my xml changed dynamically based on the key value, below is my original xml, following that is the xml i wanted to be after the xsl conversion.
original xml:
<Refd>
<randr>
<KeyPair>
<Key>CM_001</Key>
<Value>sometext</Value>
</KeyPair>
<KeyPair>
<Key>CM_002</Key>
<Value>sometext/Value>
</KeyPair>
<KeyPair>
<Key>CM_003</Key>
<Value>sometext/Value>
</KeyPair>
</randr>
</Refd>
trying to get this as below:
<Refd>
<randr>
<KeyPair_001>
<Key>CM_001</Key>
<Value>sometext</Value>
</KeyPair_001>
<KeyPair_002>
<Key>CM_002</Key>
<Value>sometext/Value>
</KeyPair_002>
<KeyPair_003>
<Key>CM_003</Key>
<Value>sometext/Value>
</KeyPair_003>
</randr>
</Refd>
trying to get the xslt working by the below , but it only gets me for just 1 tag and the others remain unchanged, can i get it to work for multiple tags. Thank you in advance
<xsl:template match="Refd/randr/KeyPair">
<xsl:variable name="ename">
<xsl:text>Key</xsl:text>
<xsl:if test="Key ='CM_001'">
<xsl:text>001</xsl:text>
</xsl:if>
</xsl:variable>
<xsl:element name="{$ename}">
<xsl:copy-of select="@*"/>
<xsl:apply-templates select="node()"/>
</xsl:element>
</xsl:template>
Upvotes: 0
Views: 35
Reputation: 117165
How about:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="KeyPair">
<xsl:element name="KeyPair{substring-after(Key, 'CM')}">
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
Note that numbering element names is considered bad practice. If your target application demands it, then it's unavoidable; but in general it is best to use an attribute for this purpose.
Upvotes: 1