XSLT:Add Attribute to XML
Posted: Mon May 10, 2021 7:11 am
Hi
I'm new to XSLT and trying to transform few xml elements as attributes. my code works but it's overriding the id attribute with dept and not showing both of them as attributes. Can you please help me
XSLT Code:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs"
version="1.0">
<xsl:output indent="yes" />
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates
select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="id" />
<xsl:template match="*[id]">
<xsl:copy>
<xsl:attribute name="id">
<xsl:value-of select="id" />
</xsl:attribute>
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
<xsl:template match="dept" />
<xsl:template match="*[dept]">
<xsl:copy>
<xsl:attribute name="dept">
<xsl:value-of select="dept" />
</xsl:attribute>
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
sample Input:
<class>
<employee>
<id>001</id>
<firstname>James</firstname>
<lastname>G</lastname>
<nickname>Jamie</nickname>
<salary>100</salary>
<dept>HR</dept>
</employee>
</class>
Expected Output:
<class>
<employee id = "001" dept="HR">
<firstname>James</firstname>
<lastname>G</lastname>
<nickname>Jamie</nickname>
<salary>100</salary>
</employee>
</class>
I'm new to XSLT and trying to transform few xml elements as attributes. my code works but it's overriding the id attribute with dept and not showing both of them as attributes. Can you please help me
XSLT Code:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs"
version="1.0">
<xsl:output indent="yes" />
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates
select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="id" />
<xsl:template match="*[id]">
<xsl:copy>
<xsl:attribute name="id">
<xsl:value-of select="id" />
</xsl:attribute>
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
<xsl:template match="dept" />
<xsl:template match="*[dept]">
<xsl:copy>
<xsl:attribute name="dept">
<xsl:value-of select="dept" />
</xsl:attribute>
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
sample Input:
<class>
<employee>
<id>001</id>
<firstname>James</firstname>
<lastname>G</lastname>
<nickname>Jamie</nickname>
<salary>100</salary>
<dept>HR</dept>
</employee>
</class>
Expected Output:
<class>
<employee id = "001" dept="HR">
<firstname>James</firstname>
<lastname>G</lastname>
<nickname>Jamie</nickname>
<salary>100</salary>
</employee>
</class>