Wednesday, April 4, 2012

Create an XMl file using java

Scenario: to create an XML file using java
JAR files required: DOM jar,JXL jar.


Java Code: 



import java.io.File;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
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.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;




public class GenerateXmlFile {

public static void main(String argv[]) throws ParserConfigurationException, TransformerException 
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Organization");
doc.appendChild(rootElement);

Attr attr = doc.createAttribute("Name");
attr.setValue("Saankya labs");
rootElement.setAttributeNode(attr);

Element Employee = doc.createElement("Employee");
rootElement.appendChild(Employee);

attr = doc.createAttribute("FirstName");
attr.setValue("XYZ");
Employee.setAttributeNode(attr);

attr = doc.createAttribute("LastName");
attr.setValue("abc");
Employee.setAttributeNode(attr);

Element Education = doc.createElement("Education");
Education.appendChild(doc.createTextNode("BE"));
Employee.appendChild(Education);


TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\Blog.xml"));

// Output to console for testing
// StreamResult result = new StreamResult(System.out);

transformer.transform(source, result);

System.out.println("File saved!");
}


}

The usual XML parsing is done using SAX PARSER or DOM parser.
DOM parser is comparatively rich in functionality,it creates a DOM tree in memory not just that it even allows to manipulate that DOM tree.
Having said that SAX parser saves a lot of space when dealing with large input files, it runs faster and also a lot more easier to learn because the API's is very simple.



Comment:Little tedious to work on if we generating large XML files but work good for small XML files