user3656511
user3656511

Reputation: 53

In XSLT, how to copy all attributes from all child nodes to root node of xml?

I want a XSLT program which will transform a XMl a file in a way that will read/extract all attributes from all child nodes(till deep level ) of root node and copy to parent node. Then remove all child nodes. Input xml

enter code here
<root>
  <a key="1"/> 
  <b key1="2">
    <c key3="3"/>
  </b>
</root> 

and output xml would be like this:

<root key="1" key1="2" key3="3" />

Upvotes: 0

Views: 1135

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117140

You could do quite simply:

XSLT 1.0

<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:template match="/root">
    <xsl:copy>
        <xsl:copy-of select="//@*"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

However, an element cannot have two attributes with the same name. If your XML has more than one instance of the same attribute, they will overwrite each other and only the last one will be present in the output.

Upvotes: 1

Related Questions