Edit XML file using the DOM in Java

In this tutorial, I will guide you how to edit an XML file using the DOM through an example is to edit the XML file has the following content:



The information will be edited

I will edit some things as follows:

  • Correct student number (attribute n0) is 2.
  • Name of student is Khanh.
  • Add email tag with value (huongdanjava.com@gmail.com)
  • Remove the age tag.

After editing, my XML file will look like this:



Edit

Similar to the tutorial on creating new XML file, to edit an XML file we also use DocumentBuilder to load the XML file and make the edit, then use the Transformer object to save the editing.

First, we will use the DocumentBuider object to create the Document object and load the XML file:

All the information we need to edit is in the <student> tag, so we have to get the information of this tag first:

Now we will update the attribute n0:

To update the <name> tag information, we have to get this tag first from the <student> tag:

Then, we will assign value to this tag as follows:

Next, we will add the <email> tag in the <student> tag:

And remove the <age> tag in the <student> tag:

OK, now that we have finished editing, the rest is to save the edited content to disk only:

The code will look like this:

Result:

Edit XML file using the DOM in Java

5/5 - (1 vote)

2 thoughts on “Edit XML file using the DOM in Java

Add Comment