Share this page 

Transform XML into CSV using XSLT Tag(s): XML


The input file
[howto.xml]
<?xml version="1.0"?>
<howto>
    <topic id="1">
        <title>Java</title>
        <url>http://www.rgagnon.com/topics/java-io.html</url>
    </topic>
    <topic id="2">
        <title>XML</title>
        <url>http://www.rgagnon.com/topics/java-xml.html</url>
    </topic>
    <topic id="3">
        <title>Javascript</title>
        <url>http://www.rgagnon.com/topics/js-language.html</url>
    </topic>
    <topic id="4">
        <title>VBScript</title>
        <url>http://www.rgagnon.com/topics/wsh-vbs.html</url>
    </topic>
</howto>
The transformation sheet
[howto.xsl]
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                              xmlns:fo="http://www.w3.org/1999/XSL/Format" >
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="/">
topic,title,url
<xsl:for-each select="//topic">
   <xsl:value-of select="@id" />
   <xsl:value-of select="concat(',' , title, ',' , url,'
')"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Using this program
[XMLToCSV.java]
package com.rgagnon.howto;

import org.w3c.dom.Document;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class XMLToCSV {
  public static void main(String args[]) throws Exception {
    File stylesheet = new File("src/howto.xsl");
    File xmlSource = new File("src/howto.xml");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(xmlSource);
    StreamSource stylesource = new StreamSource(stylesheet);
    Transformer transformer = TransformerFactory.newInstance()
          .newTransformer(stylesource);
    Source source = new DOMSource(document);
    Result outputTarget = new StreamResult(new File("/temp/howto.csv"));
    transformer.transform(source, outputTarget);
    System.out.println("Done.");
  }
}
The result is
[howoto.csv]
topic,title,url
1,Java,http://www.rgagnon.com/topics/java-io.html
2,XML,http://www.rgagnon.com/topics/java-xml.html
3,Javascript,http://www.rgagnon.com/topics/js-language.html
4,VBScript,http://www.rgagnon.com/topics/wsh-vbs.html

mail_outline
Send comment, question or suggestion to howto@rgagnon.com