How to delete child node of given node in XML file using DOM Parser in Java?
Problem Description:
<Employees>
<Employee id="1">
<name>abc</name>
<age>23</age>
</Employee >
<Employee id="2">
<name>xyz</name>
<age>29</age>
</Employee>
<Employee id="3">
<name>lmn</name>
<age>34</age>
</Employee>
<name>abc</name>
<age>23</age>
</Employee >
<Employee id="2">
<name>xyz</name>
<age>29</age>
</Employee>
<Employee id="3">
<name>lmn</name>
<age>34</age>
</Employee>
</Employees>
Here requirement is to delete child node <age>34</age> for Employee whose id is 3. Similarly user can delete any child node for any Employee.
1) Parse XML file or Create an instance of Document interface present in org.w3c.dom.* package.
For Creating an instance of Document interface we need to use DocumentBuilderFactory, DocumentBuilder classes present in javax.xml.parsers.* package and File class present in java.io.* package.Here requirement is to delete child node <age>34</age> for Employee whose id is 3. Similarly user can delete any child node for any Employee.
Steps:
1) Parse XML file or Create an instance of Document interface present in org.w3c.dom.* package.
File file = new File(XML_file_location);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);
2) Enter node id, child name. Here node means Employee and child means property of Employee.
3) Get all the child nodes Employee of root node Employees. It returns the instance of NodeList interface present in org.w3c.dom.* package.
NodeList list = document.getElementsByTagName("Employee");
4) Now one by one examine each child node Employee.
5) Create an instance of Transformer class present in javax.xml.transform.* package.
2) Enter node id, child name. Here node means Employee and child means property of Employee.
![]() |
Figure 1 |
3) Get all the child nodes Employee of root node Employees. It returns the instance of NodeList interface present in org.w3c.dom.* package.
NodeList list = document.getElementsByTagName("Employee");
4) Now one by one examine each child node Employee.
- From all the child nodes that we got in Step 3 take one child node. It returns instance of Node interface present in org.w3c.dom.* package.
- Check whether this node is Element node or not?
- If it is an Element node then typecast it and get its data (attributes and properties).
- Get its id as follows.
- Compare this id with id of given Employee.
if (String.valueOf(id).equals(element.getAttribute("id"))) {}
element.removeChild(current);
- If id found then check whether given child node exists or not.
Node current = element.getElementsByTagName(property).item(0);
- If child node exists then get previous sibling of child node as follows.
Node prev = current.getPreviousSibling();
- If sibling is text node then delete it from given node Employee.
if (prev != null && prev.getNodeType() == Node.TEXT_NODE && prev.getNodeValue().trim().length() == 0) {
element.removeChild(prev);
}
- Now delete selected child node from given node Employee.
5) Create an instance of Transformer class present in javax.xml.transform.* package.
For creating an instance of Transformer class we need to use TransformerFactory class present in javax.xml.transform.* package.
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
6) Set xml file indentation (Optional)
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
6) Set xml file indentation (Optional)
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
7) Create an instance of DOMSource class present in javax.xml.transform.dom.* package and pass instance of Document interface created in step 1.
7) Create an instance of DOMSource class present in javax.xml.transform.dom.* package and pass instance of Document interface created in step 1.
DOMSource source = new DOMSource(document);
8) Create an instance of StreamResult class present in javax.xml.transform.stream.* package.
For creating an instance of StreamResult class first we need to create an instance of File class present in java.io.* package.
File file = new File(location_of_xml_file);
StreamResult result = new StreamResult(file);
9) Transform XML Source to a Result.
transformer.transform(source, result);
8) Create an instance of StreamResult class present in javax.xml.transform.stream.* package.
For creating an instance of StreamResult class first we need to create an instance of File class present in java.io.* package.
File file = new File(location_of_xml_file);
StreamResult result = new StreamResult(file);
9) Transform XML Source to a Result.
transformer.transform(source, result);
Software Required:
- JDK
- Eclipse
- Maven
Note : I suggest to use latest version of all the software. If you need any help regarding these software installation please comment below I will help you.
pom.xml
Employee.java
DeleteEmployeeProperty.java
Output:
employee.xml
Download Project
Click here for more questions on DOM Parser.
Project Structure:
![]() |
Figure 2 |
Java Code:
employee.xml
employee.xml
12345678910111213141516<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employees>
<Employee id="1">
<name>Rohit</name>
<gender>male</gender>
<age>25</age>
<role>Programmer</role>
</Employee>
<Employee id="2">
<name>Bhavna</name>
<gender>female</gender>
<age>20</age>
<role>Student</role>
</Employee>
</Employees>
pom.xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | |
<modelVersion>4.0.0</modelVersion> | |
<groupId>com.javamultiplex</groupId> | |
<artifactId>DOM</artifactId> | |
<version>0.0.1-SNAPSHOT</version> | |
<build> | |
<pluginManagement> | |
<plugins> | |
<plugin> | |
<groupId>org.apache.maven.plugins</groupId> | |
<artifactId>maven-compiler-plugin</artifactId> | |
<version>3.6.1</version> | |
<configuration> | |
<source>1.8</source> | |
<target>1.8</target> | |
</configuration> | |
</plugin> | |
</plugins> | |
</pluginManagement> | |
</build> | |
</project> |
Employee.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javamultiplex; | |
public class Employee { | |
private int id; | |
private String name; | |
private int age; | |
private String gender; | |
private String role; | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public int getAge() { | |
return age; | |
} | |
public void setAge(int age) { | |
this.age = age; | |
} | |
public String getGender() { | |
return gender; | |
} | |
public void setGender(String gender) { | |
this.gender = gender; | |
} | |
public String getRole() { | |
return role; | |
} | |
public void setRole(String role) { | |
this.role = role; | |
} | |
@Override | |
public String toString() { | |
return "Employee[id="+getId()+", name="+getName()+", gender="+getGender()+", age="+getAge()+", role="+getRole()+"]"; | |
} | |
public int getId() { | |
return id; | |
} | |
public void setId(int id) { | |
this.id = id; | |
} | |
} |
DeleteEmployeeProperty.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javamultiplex; | |
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
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 DeleteEmployeeProperty { | |
public static void main(String[] args) throws IOException,ParserConfigurationException, SAXException, TransformerException { | |
File file = new File("src/main/resources/employee.xml"); | |
BufferedReader input = null; | |
try { | |
input = new BufferedReader(new InputStreamReader(System.in)); | |
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); | |
DocumentBuilder builder = factory.newDocumentBuilder(); | |
Document document = builder.parse(file); | |
System.out.println("Enter employee id : "); | |
int id = Integer.parseInt(input.readLine()); | |
System.out.println("Enter property name : "); | |
String property = input.readLine(); | |
boolean result = deleteEmployeePropertyFromXml(document, id, property); | |
if (result) { | |
TransformerFactory tFactory = TransformerFactory.newInstance(); | |
Transformer transformer = tFactory.newTransformer(); | |
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); | |
DOMSource source = new DOMSource(document); | |
StreamResult sResult = new StreamResult(file); | |
transformer.transform(source, sResult); | |
System.out.println("Employee property has been deleted successfully."); | |
} else { | |
System.out.println("Either employee id or property name is wrong."); | |
} | |
} finally { | |
if (input != null) { | |
input.close(); | |
} | |
} | |
} | |
private static boolean deleteEmployeePropertyFromXml(Document document,int id, String property) { | |
NodeList list = document.getElementsByTagName("Employee"); | |
boolean result = false; | |
int length = list.getLength(); | |
for (int i = 0; i < length; i++) { | |
Node node = list.item(i); | |
if (node.getNodeType() == Node.ELEMENT_NODE) { | |
Element element = (Element) node; | |
if (element.getAttribute("id").equals(String.valueOf(id))) { | |
Node current = element.getElementsByTagName(property).item(0); | |
if (current != null) { | |
Node prev = current.getPreviousSibling(); | |
if (prev != null && prev.getNodeType() == Node.TEXT_NODE && prev.getNodeValue().trim().length() == 0) { | |
element.removeChild(prev); | |
} | |
element.removeChild(current); | |
result = true; | |
break; | |
} | |
} | |
} | |
} | |
return result; | |
} | |
} |
Output:
![]() |
Figure 3 |
employee.xml
123456789101112131415 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employees>
<Employee id="1">
<name>Rohit</name>
<gender>male</gender>
<age>25</age>
<role>Programmer</role>
</Employee>
<Employee id="2">
<name>Bhavna</name>
<gender>female</gender>
<role>Student</role>
</Employee>
</Employees>
Here you can see that child node <age>20</age> has been deleted for Employee whose id is 2.Download Project
Click here for more questions on DOM Parser.
References:
https://docs.oracle.com/javase/7/docs/api/javax/xml/parsers/DocumentBuilderFactory.html
https://docs.oracle.com/javase/7/docs/api/javax/xml/parsers/DocumentBuilder.html
https://docs.oracle.com/javase/7/docs/api/javax/xml/parsers/DocumentBuilder.html
Thank you friends, I hope you have clearly understood the solution of this problem. If you have any doubt, suggestion or query please feel free to comment below. You can also discuss this solution in our forum.
How to delete child node of given node in XML file using DOM Parser in Java?
Reviewed by Rohit Agarwal
on
10/09/2017
Rating:

No comments:
Please provide your valuable comments. If you have any suggestion please share with me I will work on it and if you have any question or doubt please ask, don't hesitate. I am your friend, i will clarify all your doubts.