Tuesday, November 30, 2010

XML Writing with Java DOM Parser

I am looking for something like this kind of xml.


Some of the things in very short about the DOM parsers
1. Tree of nodes
2. Memory: Occupies more memory, preffered for small XML documents
3. Slower at runtime
4. Stored as objects
5. Programmatically easy
6. Ease of navigation

DOM which builds a data tree in memory for easier, non-sequential access to XML data fragments.

Now lets jump directly to the example.

******CREATE DOCUMENT OBJECT******

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DB docB = dbf.newDocumentBuilder();
Document doc = docB.newDocument();
******POPULATE DOCUMENT DATA******

// create the root and child tags
// create root node with the name company
Element root = doc.createElement("company");

//create a employee element
Element parent= doc.createElement("employee");

// set empid which is attribute of the element
parent.setAttribute("empid","E1");

// create child element for parent and add a textnode to it.
Element child = doc.createElement("firstname");
child.appendChild(doc.createTextNode("Deepak"));

// append the child "first name" to the parent "employee"
parent.appendChild(child);

******SAVE DOCUMENT TO FILE******
// write into the file
TransformerFactory tfac = TransformerFactory.newInstance();
Transformer transformer = tfac.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);

StreamResult streamResult = new StreamResult(new File("c:/text.xml"));

transformer.transform(source, streamResult);



Download complete example from here: Downlaod Demo Write-Read-Modify Example (Eclipse Project)