Reputation: 2277
I am trying to transform an xml where the the node contains multiple attribute .Out of which I want 2 or 3 attributes to become element and insert some extra attribute in the same element. Below is the xml structure which i want to convert
<Parent>
<NODE attr1="INDEX" attr2="0" attr3="OFF" attr4="TRANSPARENT_MODE" attr5="HIGH" attr6="0" attr7="0" attr8="TIME">
<value>0</value>
<alias>Index 0</alias>
</NODE >
</Parent>
I want to transform this xml to
<Parent>
<NODE attr2="0" attr3="OFF" attr4="TRANSPARENT_MODE" attr6="0" attr8="TIME">
<attr1 value="INDEX">
<attr5 value="HIGH">
<attr7 value="0">
<value>0</value>
<alias>Index 0</alias>
</NODE >
</Parent>
So as I had shown I only want 3 attribute i.e attr1 attr5 and attr7 to be element and other to stay as it is.For this I tried below xslt styling
<xsl:template match="Parent/NODE/@attr1">
<attr1>
<xsl:attribute name="value"><xsl:value-of select="." /></xsl:attribute>
</attr1>
</xsl:template>
But after doing this for 3 attributes other attributes are not coming in transformed xml. Any help on this will be appreciated
Upvotes: 1
Views: 76
Reputation: 7385
This is not perfect because it repeats the condition for inclusion two times, but it works:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="html" doctype-public="XSLT-compat" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="NODE">
<xsl:copy>
<xsl:for-each select="@*[name()!='attr1' and name()!='attr3']">
<xsl:copy />
</xsl:for-each>
<xsl:for-each select="@*[name()='attr1' or name()='attr3']">
<xsl:element name="{name()}">
<xsl:attribute name="value" select="."/>
</xsl:element>
</xsl:for-each>
<xsl:for-each select="node()">
<xsl:copy-of select="." />
</xsl:for-each>
</xsl:copy>
</xsl:template>
</xsl:transform>
Fiddle: http://xsltransform.net/jxDigTS/1
Upvotes: 1