Modify XML file in Java (DOM Parser)

Filed Under: Java

We can modify XML file in Java using DOM parser. We can add elements, remove elements, edit element values, edit attributes in an XML document in java using DOM Parser.

Modify XML File in Java

modify xml file in java, java edit xml, update xml file in java

Let’s say we have below source XML file. We will learn how to modify or edit this XML file in java program using DOM parser.

employee.xml


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employees>
	<Employee id="1">
		<name>Pankaj</name>
		<age>29</age>
		<role>Java Developer</role>
		<gender>Male</gender>
	</Employee>
	<Employee id="2">
		<name>Lisa</name>
		<age>35</age>
		<role>CSS Developer</role>
		<gender>Female</gender>
	</Employee>
</Employees>

We will edit the XML file with below changes.

  1. Update the “id” attribute value for all the Employee based on Gender. For Male, id will be prefixed with “M” else prefix with “F”.
  2. Update the value of “name” element by making it to upper case.
  3. Delete “gender” element as it’s not used now.
  4. Add a new element “salary” to all the employee node in the xml.

Once we make above modification to the XML, we will save it to a different file.

Here is the java program that does all the above updates using DOM Parser.

ModifyXMLDOM.java


package com.journaldev.xml;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
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.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ModifyXMLDOM {

    public static void main(String[] args) {
        String filePath = "employee.xml";
        File xmlFile = new File(filePath);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(xmlFile);
            doc.getDocumentElement().normalize();
            
            //update attribute value
            updateAttributeValue(doc);
            
            //update Element value
            updateElementValue(doc);
            
            //delete element
            deleteElement(doc);
            
            //add new element
            addElement(doc);
            
            //write the updated document to file or console
            doc.getDocumentElement().normalize();
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("employee_updated.xml"));
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(source, result);
            System.out.println("XML file updated successfully");
            
        } catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {
            e1.printStackTrace();
        }
    }

    private static void addElement(Document doc) {
        NodeList employees = doc.getElementsByTagName("Employee");
        Element emp = null;
        
        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            Element salaryElement = doc.createElement("salary");
            salaryElement.appendChild(doc.createTextNode("10000"));
            emp.appendChild(salaryElement);
        }
    }

    private static void deleteElement(Document doc) {
        NodeList employees = doc.getElementsByTagName("Employee");
        Element emp = null;
        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            Node genderNode = emp.getElementsByTagName("gender").item(0);
            emp.removeChild(genderNode);
        }
        
    }

    private static void updateElementValue(Document doc) {
        NodeList employees = doc.getElementsByTagName("Employee");
        Element emp = null;
        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            Node name = emp.getElementsByTagName("name").item(0).getFirstChild();
            name.setNodeValue(name.getNodeValue().toUpperCase());
        }
    }

    private static void updateAttributeValue(Document doc) {
        NodeList employees = doc.getElementsByTagName("Employee");
        Element emp = null;
        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            String gender = emp.getElementsByTagName("gender").item(0).getFirstChild().getNodeValue();
            if(gender.equalsIgnoreCase("male")){
                //prefix id attribute with M
                emp.setAttribute("id", "M"+emp.getAttribute("id"));
            }else{
                //prefix id attribute with F
                emp.setAttribute("id", "F"+emp.getAttribute("id"));
            }
        }
    }

}

Output modified version of the XML file from above program is given below.

employee_updated.xml


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employees>
	<Employee id="M1">
		<name>PANKAJ</name>
		<age>29</age>
		<role>Java Developer</role>
		
	<salary>10000</salary>
</Employee>
	<Employee id="F2">
		<name>LISA</name>
		<age>35</age>
		<role>CSS Developer</role>
		
	<salary>10000</salary>
</Employee>
</Employees>

That’s all for a quick example of java edit XML file using DOM parser.

Comments

  1. Shailesh says:

    Hi Pankaj,

    Can you clarify on this: Since org.w3c.dom.Document (and also Element, Node etc.) are interfaces, how is it that we are able to use them without implementation classes.

    1. Pankaj says:

      We are using implementation classes, in below lines.

      dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(xmlFile);
      

      The code is written in terms of interfaces. If you are familiar with JDBC, it’s same there as well.

  2. Rohan Sen says:

    I am having the below xml file. And I having a set of vaues for ‘name’ and ‘age’ attributes.
    For e.g. name – A, age 1, name – B, age 2. How the A and 1 will replace Pankaj and 29 respectively, and B and 2 will replace Lisa and 35 respectively

    Pankaj
    29

    Lisa
    35

  3. krunal says:

    how to use this code in java-script and html?

  4. ranadheer reddy says:

    Node importedTemplateChildNode = targetDoc.importNode(templateChildNode, true); // Importing template node to the target document(this solves wrong_DOCUMENT_ERR:)

    targetParentNode.replaceChild(importedTemplateChildNode, targetChildnode);
    // Replace target child node with the template node

    Transformer tranFac =TransformerFactory.newInstance().newTransformer();
    tranFac.transform(new DOMSource(targetDoc), new StreamResult(new FileWriter(targetXmlFile)));

  5. tamilselvan says:

    I want to delete or update particular employee then what can i do

  6. Venessa Johnson says:

    Hi:
    Thank you so much for sharing your code….I created similar code to update an XML file to replace ‘&’ with ‘&’ in a tag. When I run it in JDeveloper, it gave me an error. It does not like the ‘&’ when it tries to retrieve the content of the ‘Company_Name’ tag.

    Here is part of my XML file that I am trying to replace

    A & W

    I want to change it to:
    A & W

    Here is my code:

    for (final File fileEntry : folder.listFiles()) {
    doc = dBuilder.parse(fileEntry);
    nList = doc.getElementsByTagName(“Company_Name”);
    str = nList.item(0).getTextContent();
    str = str.replaceAll(“&”,”&”);
    nList.item(o).setTextContent(str);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = TransformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(fileEntry);
    }

    Here is the error I got:
    [Fatal Error] test.xml: 1:1661: The entity name must immediately follow the ‘&’ in the entity reference….org.xml.sax.SAXParseException; systemId: file:/C:/test.xml…….follow the ‘&’ in the entity reference.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse (DOMParser.java:257)

    Do you know how I can change my code to change ‘&’ to ‘&amps’?

    Thanks for any help you can provide…
    Venessa

  7. Baudoin says:

    This is a concrete example.
    thank you

  8. Shreyans says:

    Getting error null pointer..I think code couldn’t able read xml

    1. Shreyans says:

      in my case doc object is null..xml path is proper.

    2. MinhPhuong - Vietnamese says:

      i think you have mistake at getElementsByTagName(“Employee”). It distinguish between uppercase and lowercase.

  9. visit here says:

    It’s an remarkable paragraph for all the online viewers;
    they will take benefit from it I am sure.

  10. Hai says:

    You have a tutorial to add, edit, delete the XML document using the DOM writes on her an Application for java? Share let me code!

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages