How to modify XML using DOM in Java

Although the main purpose of XML documents is to store lightweight data for faster processing, they are still used in some small applications as a data store which requires dynamic modification. In this article we show how to modify an XML document using DOM in Java.

You can still refer to previous articles which cover how to create and parse XML documents using DOM.

1- Students.xml

Consider we have the following XML document:

Throughout this tutorial, we’re going to do the following modifications on the above XML:

  • Add an attribute to an existing element.
  • Modify the content of an existing element.
  • Add a child element to an existing element.
  • Delete an existing element

2- Add attribute

In the following code block we set a specific student as graduated through iterating over the student elements and calling setAttribute() on the required student.

3- Modify existing element

In the following code block we modify the first name of a specific student. To do so, we iterate over student elements and call setTextContent() on the “name” element of the appropriate student.

4- Add an element

In the following code block we add a new child element called “lastName” to a specific student. To do so, we iterate over student elements and when we find the requested student, we create an element using doc.createElement() and then append it to the student element using appendChild().

5- Delete existing element

In the following code block, we delete the “lastName” element of a specific student. To do so, we iterate over student elements and call removeChild() on the “lastName” element of the requested student.

6- Demo

For demo purposes, we create a main method which reads students.xml document and modifies it using the above methods as the following:

After executing the above main method, students.xml would look like the following:

7- Source Code

You can download the source code from this repository: Read-XML

 

Hussein Terek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

Leave a Reply

avatar