DOM parser to modify xml file in java

The DOM refers to Document Object Model. The DOM parses the XML file, creates the DOM objects and loads it into the memory in the tree structure.
Note: DOM is simple and easy to use but it consume lots of memory and slow.
The XML refers to the EXtensible Markup Language which is used to store and transport the data. XML not provides any predefined tags. We have to define our own tags. Every opening XML tag must have a closing tag. XML tags are case sensitive and must be completely nested.

Steps to modify XML file:

1. Create a Document with DocumentBuilder class.
2. Fetch the xml elements.
3. Update the xml elements.
4. Write the whole data on a file using Transformer class.

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
* This class is used to modify XML document using DOM parser.
* @author javawithease

public class DOMParserModifyTest {
public static void main(String args[]) {
try {
//File Path
String filePath = "D:\\class.xml";
//Read XML file.
File inputFile = new File(filePath);
//Create DocumentBuilderFactory object.
DocumentBuilderFactory dbFactory =
//Get DocumentBuilder object.
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
//Parse XML file.
Document document = dBuilder.parse(inputFile);
//Get element by tag name.
Node students =
//Update students attribute.
NamedNodeMap attr = students.getAttributes();
Node nodeAttr = attr.getNamedItem("className");
nodeAttr.setTextContent("CSE 1st");
//Get student element list.
NodeList list = students.getChildNodes();
//Iterate and process student.
for (int temp = 0; temp < list.getLength(); temp++) {
Node node = list.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element stuElement = (Element) node;
if ("studentName".equals(stuElement.getNodeName())) {
stuElement.setTextContent("Swati Aneja");
//Save changes into XML file.
TransformerFactory transformerFactory =
Transformer transformer=
DOMSource source = new DOMSource(document);
StreamResult result=new StreamResult(new File(filePath));
transformer.transform(source, result);
//For console Output.
StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(source, consoleResult);
} catch (Exception e) {


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<students className="CSE 1st">
<studentName>Swati Aneja</studentName>
<studentName>Nidhi Gupta</studentName>

No comments: