Page 1 of 1

XSLT:Add Attribute to XML

Posted: Mon May 10, 2021 7:11 am
by proxyUser
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>

Re: XSLT:Add Attribute to XML

Posted: Mon May 10, 2021 9:50 am
by tavy
Hello,

I think the stylesheet should be something like this:

Code: Select all

<?xml version="1.0" encoding="UTF-8"?>
<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="employee">
        <xsl:copy>
            <xsl:attribute name="id">
                <xsl:value-of select="id"/>
            </xsl:attribute>
            <xsl:attribute name="dept">
                <xsl:value-of select="dept"/>
            </xsl:attribute>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="id |dept"/>
    
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
I recommend you to address this questions on the XSLT List (xsl-list@lists.mulberrytech.com), there are more experienced users to answer.

Best Regards,
Octavian

Re: XSLT:Add Attribute to XML

Posted: Mon May 10, 2021 8:35 pm
by proxyUser
Thanks Tavy. It's working fine for me. I appreciate your help :D