wood burning stoves 2.0*
The moose likes XML and Related Technologies and the fly likes Q: XML to CSV Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "Q: XML to CSV" Watch "Q: XML to CSV" New topic
Author

Q: XML to CSV

Chuck Zheng
Greenhorn

Joined: Apr 03, 2004
Posts: 5
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
Lasse Koskela
author
Sheriff

Joined: Jan 23, 2002
Posts: 11962
    
    5
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...


Author of Test Driven (2007) and Effective Unit Testing (2013) [Blog] [HowToAskQuestionsOnJavaRanch]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Q: XML to CSV
 
Similar Threads
XSLT : Grouping Child Nodes...
xhtml to xhtml using xslt
if else if check it please.
[XSL] XML to XML without empty element
If not null - need help with rule.....