Java Integration
Transform Anything with Java
Creating XML with DOM Parser
1. Create an Eclipse Project named DOM Parser.
2. Create 3 new classes inside the package com.javatweaks.dom
Items.java
DOMCreator.java (with main)
createXMLDOM.java
3. Let us define the createXMLDOM class first.
4. We will create a method createXMLDoc() that will return a Document object. Note we will use the package com.w3c.dom for our application.
5. We have to create 3 objects sequentially.
DocumentBuilderFactory to create a factory object
DocumentBuilder to create a builder object
Document to create the XML document
We will do that by adding the below lines.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
6. Now we will have to define the root element for the XML document that we created. For that we will use the Element object from com.w3c.dom
Element rootElement = doc.createElement("items");
7. Now that we have created the root element, we have to attach the same to the Document. For that
doc.appendChild(rootElement);
The code will be like.
package com.javatweaks.dom;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class createXMLDOM {
public Document createXMLDOC() throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element rootElement = doc.createElement("items");
doc.appendChild(rootElement);
return doc;
}
}
7. Now let us use this class in the main method. Goto the class DOMCreator and create an instance for the class createXMLDOM
8. We cannot print the document. We have to do something here. Create a Node object and use getFirstChild() method to access node.
Below is the code.
package com.javatweaks.dom;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
public class DOMCreator {
public static void main(String[] args) throws ParserConfigurationException {
createXMLDOM dom = new createXMLDOM();
Document doc = dom.createXMLDOC();
Node root = doc.getFirstChild();
System.out.println(root.getNodeName());
}
}
Execute the code and print the same. It will just print the node name as item
Now let us add data elements and attributes with DOM
9. For reading the XML let us not write anothe parser. Let use use our previouse project and import it to this project and reuse the same. Here is the link
10. Use the below lines to do so.
String filename = "C:\\Users\\xxx\\Documents\\Java_XML\\items.xml";
SAXItemsHandler saxHandler = new SAXItemsHandler();
List<Items> data = saxHandler.readDataFromXML(filename);
11. Update the createXMLDOC() method to get List<Items> as parameter like createXMLDOC(List<Items> data)
12. In the main method call the createXMLDOC() with parameter like this. Document doc = dom.createXMLDOC(data);
13. create a foreach loop to iterate through items in the mothod createXMLDOC().
for (Items item : data) {
Element itemElement = doc.createElement("item");
rootElement.appendChild(itemElement);
String idString = Integer.toString(item.getId());
rootElement.setAttribute(Items.ID, idString);
}
14. Now let us go back to the main method and print them. In order to do that, we have to go through this hierarchy.
Get the root node > create a NodeList object to access the item and Node to access each item.
NodeList nodes = root.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node child = nodes.item(i);
System.out.println(child.getNodeName());
}
Now we have gone till the attribute. Now let us add data in the form of more child items. Let us refactor the code a little.
15. Select the below two lines > Right click > Refactor > Extract Method.
Element itemElement = doc.createElement("item");
rootElement.appendChild(itemElement);

16. We can see that a new method addElement is created as below.
public Element addElement(Element rootElement) {
Element itemElement = doc.createElement("item");
rootElement.appendChild(itemElement);
return itemElement;
}
17. The final code for both the programs are as below.
package com.javatweaks.dom;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.javatweaks.sax.read.Items;
public class createXMLDOM {
Document doc;
public Document createXMLDOC(List<Items> data) throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.newDocument();
Element rootElement = doc.createElement("items");
doc.appendChild(rootElement);
for (Items item : data) {
Element itemElement = addElement(rootElement, "item","");
String idString = Integer.toString(item.getId());
rootElement.setAttribute(Items.ID, idString);
addElement(itemElement, Items.NAME, item.getName());
addElement(itemElement, Items.MAN, item.getManufacturer());
addElement(itemElement, Items.PRICE, item.getPrice());
}
return doc;
}
public Element addElement(Element parent, String elementName, String textValue) {
Element childElement = doc.createElement(elementName);
childElement.setTextContent(textValue);
parent.appendChild(childElement);
return childElement;
}
}
package com.javatweaks.dom;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.javatweaks.sax.read.Items;
import com.javatweaks.sax.read.SAXItemsHandler;
public class DOMCreator {
public static void main(String[] args) throws ParserConfigurationException, IOException {
String filename = "C:\\Users\\xxxx\\Documents\\Java_XML\\items.xml";
SAXItemsHandler saxHandler = new SAXItemsHandler();
List<Items> data = saxHandler.readDataFromXML(filename);
createXMLDOM dom = new createXMLDOM();
Document doc = dom.createXMLDOC(data);
Node root = doc.getFirstChild();
System.out.println(root.getNodeName());
NodeList nodes = root.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node child = nodes.item(i);
System.out.println(child.getNodeName());
System.out.println(child.getTextContent());
}
}
}
Now if we run the program the output will be
items
item
iPhone 5 Apple Inc 600
item
iPhone 6 Apple Inc 700
item
Moto X Motorola 200
item
Moto G Motorola 450
item
Samsung S4 Samsung Corp 550