简体   繁体   中英

Changing XML element tag using XSLT

If possible I would like to change an XML tag name using XSLT. Using the value assigned to designation I would like for that to be the new tag name in the XML output.

The XML:

<?xml version="1.0" encoding="UTF-8"?>
<x>
    <y>
        <z value="john" designation="manager"></z>
        <z value="mike" designation="associate"></z>
        <z value="dave" designation="associate"></z>
    </y>
</x>

The XSL:

<?xml version="1.0" encoding="UTF-8"?>
<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="*" />

    <xsl:param name="request_tag"/>
    <xsl:template match="x">
        <employees>
            <xsl:apply-templates />
        </employees>    
    </xsl:template>

    <xsl:template match="y">
        <employee>
            <xsl:apply-templates />
        </employee> 
    </xsl:template> 

    <xsl:template match="z" value="{@value}">
        <xsl:element name="{$request_tag}">
            <xsl:value-of select="@value"/>
            <xsl:apply-templates />
        </xsl:element>    
    </xsl:template>

</xsl:stylesheet>

Desired Result in XML form:

<?xml version="1.0" encoding="UTF-8"?>
<employees>
    <employee>
        <manager>john</manager>
        <associate>mike</associate>
        <associate>dave</associate>
    </employee>
</employees>

Using the value assigned to designation I would like for that to be the new tag name in the XML output.

So why don't you do exactly what you said:

<xsl:template match="z">
    <xsl:element name="{@designation}">
        <xsl:value-of select="@value"/>
    </xsl:element>    
</xsl:template>

I don't see what is the purpose of:

<xsl:param name="request_tag"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM