Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert specific attribute into element

Tags:

xml

xslt

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.

like image 382
Sasha Korman Avatar asked Jan 24 '26 12:01

Sasha Korman


1 Answers

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>
like image 110
ColinE Avatar answered Jan 26 '26 03:01

ColinE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!