Wednesday 22 May 2019

Java: Convert xml file to csv file in Java


By feeding corresponding xsl file, you can convert the xml data to csv file format.

studentData.xml
<?xml version="1.0"?>
<students>
 <student>
     <firstname>Rama</firstname>
     <middlename>Krishna</middlename>
     <lastname>Ponnam</lastname>
     <age>33</age>
 </student>

 <student>
     <firstname>Sowmya</firstname>
     <middlename>Krishna</middlename>
     <lastname>Ponnam</lastname>
     <age>25</age>
 </student>
</students>


studentData.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="/">firstname,middlename,lastname,age
<xsl:for-each select="/students/student">
<xsl:value-of select="concat(firstname,',',middlename,',',lastname,',',age,'&#xA;')"/>
</xsl:for-each>
</xsl:template>

</xsl:stylesheet>


App.java
package com.sample.app;

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;

public class App {

 public static void main(String args[]) throws Exception {
  File stylesheet = new File("/Users/krishna/Documents/studentData.xsl");
  File xmlSource = new File("/Users/krishna/Documents/studentData.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("/Users/krishna/Documents/result.csv"));
  transformer.transform(source, outputTarget);
 }
}

Run App.java.


Open 'result.csv', you can see the following content.

firstname,middlename,lastname,age
Rama,Krishna,Ponnam,33
Sowmya,Krishna,Ponnam,25


You may like



No comments:

Post a Comment