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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can XSLT do this?

Status
Not open for further replies.

SAMWJ

Programmer
Feb 17, 2004
5
US
Can I use XSLT to convert XML to a comma delimited flat file?
 
Yes, the simplest one I could think of is:
make a new line for each childnode of the rootnode, and then parse all it's childnodes.
A problem might be: what do you want to do with grandchildren etc. I decided to leave them out.
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 = "text" />
  <xsl:template match="/">
  <!-- for each child of rootnode -->
   	<xsl:for-each select="/*/*">
   	<!-- for each child that doesn't contain anyting else -->
   	  <xsl:for-each select="*[not(*)]">
   	    <xsl:value-of select="."/>
            <!-- add comma if not last node -->
   	    <xsl:if test="position() != last()">
   		  <xsl:text>,</xsl:text>
	    </xsl:if>
	  </xsl:for-each>
	  <!-- new line -->
	  <xsl:text>&#xa;</xsl:text>
	</xsl:for-each>
  </xsl:template>   
</xsl:stylesheet>
I have tried to save ADODB-recordsets by saving them in an MSXML-document and transforming them to csv using XSLT.
It was a bit more complicated then this example, but still not too difficult. However, it got rather slow when the recordset contained a few hundred records, coding a routine in VB was just as easy and a lot faster...
 
Thank you very much this helps a great deal.

Best Regards!
 
How to get the XML tags as header in CSV along with the aboe solution given by gel?
 
This will parse the tree and output name,value:
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:output method="text"/>
  <xsl:template match="@*|node()">
    <xsl:if test="string(name(.)) != '' and string(text()) != ''">
      <xsl:value-of select="name(.)"/>
      <xsl:text>,</xsl:text>
      <xsl:value-of select="text()"/>
      <xsl:text>,</xsl:text>
    </xsl:if>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:template>
</xsl:stylesheet>

Jon

"I don't regret this, but I both rue and lament it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top