Friday, April 04, 2014

Create an XML file using Java

The purpose of this exercise is to crate an XML file using Java code.

Once we will understand the functionality of this code we will further leverage this to create an XML document at run time from a csv file.

Let's first see how to create an xml document from Java.

For more details on the same you can check the Oracle official site to get more details

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class generateXML {
public void createXML() {
try {

DocumentBuilderFactory documentFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder =
documentFactory.newDocumentBuilder();

// define root elements
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("Employee");
document.appendChild(rootElement);


// firstname
Element firstname = document.createElement("FirstName");
firstname.appendChild(document.createTextNode("Raj"));
rootElement.appendChild(firstname);

// lastname
Element lastname = document.createElement("LastName");
lastname.appendChild(document.createTextNode("Malhotra"));
rootElement.appendChild(lastname);


// writing to system output
TransformerFactory transformerFactory =
TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
transformer.transform(domSource, result);

} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}

public static void main(String[] args) {
generateXML gml = new generateXML();
gml.createXML();
}

}


When you will execute this code you will get the following output

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employee>
<FirstName>Raj</FirstName>
<LastName>Malhotra</LastName>
</Employee>

Now we will use this concept to see if we can dynamically pass values to this code and generate an XML document out of it.


No comments: