• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Q: XML to CSV

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,
I am a newbie to XSLT. Just try to convert following XML files to csv
<?xml version="1.0" encoding="UTF-8"?>
<DEP>
<Department>
<DEP_NO>1</DEP_NO>
<DEP_NAME>Grocery</DEP_NAME>
</Department>
<Department>
<DEP_NO>2</DEP_NO>
<DEP_NAME>Frozen</DEP_NAME>
</Department>
</DEP>
convert to
1,Grocery
2,Frozen
I also need to convert another similar XML file:
<?xml version="1.0" encoding="UTF-8"?>
<DIV>
<Division>
<DIV_NO>1</DIV_NO>
<DIV_NAME>Juice</DIV_NAME>
</Division>
<Division>
<DIV_NO>2</DIV_NO>
<DIV_NAME>Pasta</DIV_NAME>
</Division>
</DIV>
convert to
1,Juice
2,Pasta
I found some handy work on www.javaranch.com and modified as bellow and got it working:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl utput method="text"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:for-each select="DEP/Department|DIV/Division">
<xsl:apply-templates select="*"/>
</xsl:for-each>
</xsl:template>
<xsl:template match="*">
<xsl:choose>
<!-- No comma on the last element -->
<xsl:when test="position()=last()"><xsl:value-of select="."/><xsl:text>
</xsl:text>
</xsl:when>
<!-- Comma required. Not the last element -->
<xsl therwise><xsl:value-of select="."/>,</xsl therwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
My question is how not to write "DEP/Department|DIV/Division" in the xsl:for-each?
this is because I have more similar format files to process. any functions I can use?
Or there are even better solution out there? I wish some kind sole can shed some light
for me.
Thanks very much in advance
Chuck
 
author
Posts: 11962
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Would it be possible to convert those DIV, DEP, etc. into parameters which you specify when running the XSLT engine? I'm not sure if it's possible to use input parameters for this particular purpose...
 
Thanks tiny ad, for helping me escape the terrible comfort of this chair.
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic