XML DOM Parser in Java
In this section we are discussing about XML DOM Parser in Java. DOM is the abbreviation of Document Object Model. XML DOM in Java is available with JDK itself .This parser is not suitable if we need to manipulate XML file of large size. Because if we read an XML file using DOM parser , then it loads into memory after parsing.Then traversal through is easy . But for large sized files , loading the entire content to memory is not feasible always.
Reading XML File using DOM Parser
Now let us see how to read an XML file using DOM Parser. The steps for reading an XML are:
1)Create DocumentBuilderFactory and DocumentBuilder objects
2)Create a document using the DocumentBuilder object created earlier by passing the input XML file as argument.
3)Find the nodes of the document
4)Find each element in a node
5)Iterate through all nodes till the end
Now let us see the student.xml. It is giving as the input to Java program.
The XML document contains details of students in a school.As of now I just included details of only one student.We can give any number of student elements under the school tag.Now see the Java code to parse the student.xml
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
public class XMLReadDOM {
public XMLReadDOM() {
}
public void readXML() {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("C:\\Users\\My PC\\Projects\\Sample\\files\\student.xml"));
NodeList list = document.getElementsByTagName("student");
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println("Id = " + element.getAttribute("id"));
System.out.println("Name = " + element.getElementsByTagName("name").item(0).getTextContent());
System.out.println("Class / Batch = " + element.getElementsByTagName("class").item(0).getTextContent());
System.out.println("Division = " + element.getElementsByTagName("division").item(0).getTextContent());
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
XMLReadDOM xmlReadDOM = new XMLReadDOM();
xmlReadDOM.readXML();
}
}
Now let us see the output.
Output
Id = 1
Name = Bijoy
Class / Batch = 10
Division = A
You can add more students to the XML file and verify the result.
For example if I added one more student in XML , then the student.xml:
Now the output will become:
Id = 1
Name = Bijoy
Class / Batch = 10
Division = A
Id = 2
Name = Karthik
Class / Batch = 10
Division = B
Now let us see how to write data to an XML file using XML DOM Parser in Java.
Writing to XML file using DOM
The steps in writing data to an XML file are :
1)Create DocumentBuilderFactory and DocumentBuilder objects.
2)Create Document object.
3)Construct the document from top to bottom.
4)Create TransFormerFactory and Transform objects to transform the created Document object to file
5)Transform the document to xml file.
The Java code is shown below. It creates s student1.xml in a path mentioned in the code.
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
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 java.io.File;
public class XMLWriteDOM {
public XMLWriteDOM() {
}
public void writeXML() {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element baseElement = document.createElement("school");
document.appendChild(baseElement);
Element student = document.createElement("student");
baseElement.appendChild(student);
Attr attr = document.createAttribute("id");
attr.setValue("1");
student.setAttributeNode(attr);
Element name = document.createElement("name");
name.appendChild(document.createTextNode("Bijoy"));
student.appendChild(name);
Element batch = document.createElement("class");
batch.appendChild(document.createTextNode("10"));
student.appendChild(batch);
Element division = document.createElement("division");
division.appendChild(document.createTextNode("A"));
student.appendChild(division);
TransformerFactory tfrFactory = TransformerFactory.newInstance();
Transformer transformer = tfrFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(new File("C:\\Users\\My PC\\Projects\\Sample\\files\\student1.xml"));
transformer.transform(domSource, streamResult);
System.out.println("Done");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
XMLWriteDOM xmlWriteDOM = new XMLWriteDOM();
xmlWriteDOM.writeXML();
}
}
Now let us check for the student1.xml file in the mentioned path of StreamResult object.
student1.xml
See also: