I need to convert specific XML attribute into XML element. The input XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<filter query="select" name="some name"/>
My desire output looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<filter name="some name">
<query>select</query>
</filter>
I'm using the following XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml">
<xsl:strip-space elements="*"/>
<xsl:output indent="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/filter/@query">
<xsl:element name="{name(.)}">
<xsl:value-of select="."/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
However when I apply this XSLT to the provided example the name attribute disappears:
<?xml version="1.0" encoding="UTF-8"?>
<filter>
<query>select</query>
</filter>
If I change the attributes ordering, i.e. put 'name' before 'query' everything works perfectly. I try to solve it but my XSLT knowledge is very limited. Please help. Thanks in advance.
This should give you the required output:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*"/>
<xsl:output indent="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- match the filter element -->
<xsl:template match="filter">
<!-- output a filter element -->
<xsl:element name="filter">
<!-- add the name attribute, using the source name attribute value -->
<xsl:attribute name="name">
<xsl:value-of select="@name"/>
</xsl:attribute>
<!-- add the query child element, using the source query attribute value -->
<xsl:element name="query">
<xsl:value-of select="@query"/>
</xsl:element>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With