XSLT:Add Attribute to XML

Questions about XML that are not covered by the other forums should go here.
proxyUser
Posts: 2
Joined: Mon May 10, 2021 5:54 am

XSLT:Add Attribute to XML

Post 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>
tavy
Posts: 364
Joined: Thu Jul 01, 2004 12:29 pm

Re: XSLT:Add Attribute to XML

Post 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
Octavian Nadolu
<oXygen/> XML Editor
http://www.oxygenxml.com
proxyUser
Posts: 2
Joined: Mon May 10, 2021 5:54 am

Re: XSLT:Add Attribute to XML

Post by proxyUser »

Thanks Tavy. It's working fine for me. I appreciate your help :D
Post Reply