Modify XML file in Java (DOM Parser) With Examples

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

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

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

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

employee_updated.xml

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

By admin

Leave a Reply