Link to home
Start Free TrialLog in
Avatar of Alex A
Alex A

asked on

XML: writing xslt to transform xmlelement into xmlattribute

Existing XML:

<ROOT>
   <Element1>
      <Element2>
         Value
      </Element2>
   </Element1>
</ROOT>

Transformed XML should be like this:
<ROOT>
   <Element1 Element2="Value">
   </Element1>
</ROOT>

Thank you for your help.



Avatar of kmartin7
kmartin7
Flag of United States of America image

There are several ways to do what you are asking. If you want a static method, then the following will work:

<?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" indent="yes"/>

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

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


<xsl:template match="Element1">
      <Element1>
            <xsl:attribute name="Element2"><xsl:value-of select="Element2"/></xsl:attribute>
      </Element1>
</xsl:template>

</xsl:stylesheet>

You can actually match many elements and use the value of name() or local-name(), and grab the following element's value as an attribute value. Without knowing more about what your specific needs are, the above is a rudimentary but working example.

HTH,

kmartin7
Avatar of Alex A
Alex A

ASKER

Thank you kmartin7.
Existing XML is actually like this:
<ROOT>
   <Element1>
      <Element2>
         Value
      </Element2>
   </Element1>
   <Element3>Value</Element3>
   ...
   <ElementN>Value</ElementN>
</ROOT>

Element2 will be always the same. All other elements can have different names in different XML files. I need solution to be as generic as possible.
ASKER CERTIFIED SOLUTION
Avatar of Gertone (Geert Bormans)
Gertone (Geert Bormans)
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
so you would like it to iterate to all nodes ?
quasar_ee:

Geert's solution will work for you, regarding your last comment.

kmartin7