In this article, we will learn how to update or modify the existing XML file in Java using DOM Parser. In this example, we have a list of User elements in the XML file and we will modify these User elements in XML with Java program.
We want to change following for every User element in the XML.
- Add a new element
- Update existing element value
- Delete existing element
Development Process Steps
- Existing users.xml File
- Program to update existing XML file using DOM Parser
- Updated users.xml File
1. Existing users.xml File
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.
<?xml version="1.0" encoding="UTF-8"?>
<Users>
<User>
<id>1</id>
<firstName>Ramesh</firstName>
<lastName>Fadatare</lastName>
<age>28</age>
<gender>Male</gender>
</User>
<User>
<id>2</id>
<firstName>John</firstName>
<lastName>Cena</lastName>
<age>45</age>
<gender>Male</gender>
</User>
<User>
<id>3</id>
<firstName>Tom</firstName>
<lastName>Cruise</lastName>
<age>40</age>
<gender>Male</gender>
</User>
</Users>
2. Program to Update Existing XML File using DOM Parser
Here is the java program that does all the above updates using DOM Parser.
package net.javaguides.javaxmlparser.dom;
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.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
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 ModifyXMLFileInJava {
public static void main(String[] args) {
String filePath = "users.xml";
File xmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
// parse xml file and load into document
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
// update Element value
updateElementValue(doc);
// delete element
deleteElement(doc);
// add new element
addElement(doc);
// write the updated document to file or console
writeXMLFile(doc);
} catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {
e1.printStackTrace();
}
}
private static void writeXMLFile(Document doc)
throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException {
doc.getDocumentElement().normalize();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("users_updated.xml"));
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
System.out.println("XML file updated successfully");
}
/**
* Add a new element salary to user element.
* @param doc
*/
private static void addElement(Document doc) {
NodeList users = doc.getElementsByTagName("User");
Element emp = null;
// loop for each user
for (int i = 0; i < users.getLength(); i++) {
emp = (Element) users.item(i);
Element salaryElement = doc.createElement("salary");
salaryElement.appendChild(doc.createTextNode("10000"));
emp.appendChild(salaryElement);
}
}
/**
* Delete gender element from User element
* @param doc
*/
private static void deleteElement(Document doc) {
NodeList users = doc.getElementsByTagName("User");
Element user = null;
// loop for each user
for (int i = 0; i < users.getLength(); i++) {
user = (Element) users.item(i);
Node genderNode = user.getElementsByTagName("gender").item(0);
user.removeChild(genderNode);
}
}
/**
* Update firstName element value to Upper case.
* @param doc
*/
private static void updateElementValue(Document doc) {
NodeList users = doc.getElementsByTagName("User");
Element user = null;
// loop for each user
for (int i = 0; i < users.getLength(); i++) {
user = (Element) users.item(i);
Node name = user.getElementsByTagName("firstName").item(0).getFirstChild();
name.setNodeValue(name.getNodeValue().toUpperCase());
}
}
}
3. Updated users.xml File
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Users>
<User>
<id>1</id>
<firstName>RAMESH</firstName>
<lastName>Fadatare</lastName>
<age>28</age>
<salary>10000</salary>
</User>
<User>
<id>2</id>
<firstName>JOHN</firstName>
<lastName>Cena</lastName>
<age>45</age>
<salary>10000</salary>
</User>
<User>
<id>3</id>
<firstName>TOM</firstName>
<lastName>Cruise</lastName>
<age>40</age>
<salary>10000</salary>
</User>
</Users>
Note that we have added a new "salary" field to the User element, we have updated firstName from lower case to upper case and we deleted gender element from user tag.
Check out previous articles - How to Read XML File in Java using DOM Parser and How to Create XML File in Java using DOM Parser
Great tutorial, many thanks!
ReplyDeleteWhat about deleting a user? (e.g. deleting user with id=1)
I am looking for the same. By any chance did yu got the answer?
DeleteMy xml is bit different. I want to remove the tag and its child tags based on its id.
ReplyDelete#Delete User with Id = 1
Ramesh
Fadatare
28
Male
John
Cena
45
Male
Tom
Cruise
40
Male
Can you help me with this pls?