Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Basic XSLT 1

Status
Not open for further replies.

SiJP

Programmer
May 8, 2002
708
GB
I'm a complete beginner at xslt, so it comes as no suprise that I'm struggling to understand how to achieve a task.


Take the following XML:


<DataHeader>
<DataDetails>
<F1>12345</F1>
<F2>More Data</F2>
</DataDetails>
</DataHeader>


I need to write an xsl doc that converts it to this structure:


<?xml version="1.0" encoding="UTF-8"?>
<new>
<cols>
<col name="F1">12345</col>
<col name="F2">More Data</col>
</cols>
</new>

Really appreciate some help in doing this!

------------------------
Hit any User to continue
 
Code:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="[URL unfurl="true"]http://www.w3.org/1999/XSL/Transform">[/URL]
<xsl:output method = "xml" />
 
 <xsl:template match="/">
  <!-- always create elements new/cols -->
  <xsl:element name="new">
   <xsl:element name="cols">
    <!-- for each node in DataHeader/DataDetails ... -->
    <xsl:for-each select = "DataHeader/DataDetails/*">
     <!-- create an element with the name of current node -->
     <xsl:element name="{name()}">
      <!-- and put the value of current node in -->
      <xsl:value-of select="."/>
     </xsl:element>
    </xsl:for-each>
   </xsl:element>
  </xsl:element>
 </xsl:template>
</xsl:stylesheet>
good luck
 
Thanks Jel - I had to tweak a few things, but got the general idea of layout etc from your post - definately set me on a winning track.

For those interested, the XSLT 2nd Edition Programmers Reference (Michael Kay, (C) 2001 Wrox Press) is an excellant resource for developers working with xslt.

------------------------
Hit any User to continue
 
You don't need the element tags:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="[URL unfurl="true"]http://www.w3.org/1999/XSL/Transform">[/URL]
  <xsl:template match="/">
    <new>
      <cols>
        <xsl:for-each select="DataHeader/DataDetails/*">
          <col name="{name(.)}">
            <xsl:value-of select="."/>
          </col>
        </xsl:for-each>
      </cols>
    </new>
  </xsl:template>
</xsl:stylesheet>

Jon

"There are 10 types of people in the world... those who understand binary and those who don't.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top