Convert an XML file to CSV file using java Convert an XML file to CSV file using java xml xml

Convert an XML file to CSV file using java


here's a working example, data.xml has your data:

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;import org.w3c.dom.Document;class Xml2Csv {    public static void main(String args[]) throws Exception {        File stylesheet = new File("src/main/resources/style.xsl");        File xmlSource = new File("src/main/resources/data.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("/tmp/x.csv"));        transformer.transform(source, outputTarget);    }}

style.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="/">Host_Name,IP_address,OS,Load_avg_1min,Load_avg_5min,Load_avg_15min<xsl:for-each select="//Host"><xsl:value-of select="concat(Host_Name,',',IP_address,',',OS,Load_avg_1min,',',Load_avg_5min,',',Load_avg_15min,'&#xA;')"/></xsl:for-each></xsl:template></xsl:stylesheet>

output:

Host_Name,IP_address,OS,Load_avg_1min,Load_avg_5min,Load_avg_15minsrv001001,10.1.2.3,Windows1.3,2.5,1.2srv001002,10.1.2.4,Linux1.4,2.5,1.2srv001003,10.1.2.5,Linux3.3,1.6,1.8srv001004,10.1.2.6,Linux2.3,4.5,4.2


Three steps:

  1. Parse the XML file into a java XML library object.
  2. Retrieve relevant data from the object for each row.
  3. Write the results to a text file using native java functions, saving with *.csv extension.


Your best best is to use XSLT to "transform" the XML to CSV. There are some Q/As on so (like here) that cover how to do this. The key is to provide a schema for your source data so the XSLT transform process knows how to read it so it can properly format the results.

Then you can use Xalan to input the XML, read the XSLT and output your results.