How to delete attribute of given node in XML file using DOM parser in Java?
Problem Description:
<Employees>
<Employee id="1" language="hindi">
<name>abc</name>
<age>23</age>
</Employee >
<Employee id="2" language="english">
<name>xyz</name>
<age>29</age>
</Employee>
<Employee id="3" language="hindi">
<name>lmn</name>
<age>34</age>
</Employee>
<name>abc</name>
<age>23</age>
</Employee >
<Employee id="2" language="english">
<name>xyz</name>
<age>29</age>
</Employee>
<Employee id="3" language="hindi">
<name>lmn</name>
<age>34</age>
</Employee>
</Employees>
Here each Employee node has 2 attributes id and language. But now my requirement is to delete attribute language for Employee whose id is 2. Similarly user can delete any attribute (except id) of any given Employee node.
Note : Don't delete attribute id because it is unique key for identifying each Employee.
Here each Employee node has 2 attributes id and language. But now my requirement is to delete attribute language for Employee whose id is 2. Similarly user can delete any attribute (except id) of any given Employee node.
Note : Don't delete attribute id because it is unique key for identifying each Employee.
Steps:
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.
File file = new File(XML_file_location);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);
2) Enter node id and attribute name. Here node means 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 and attribute name. Here node means 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"))) {}
- If id found then get all attribute of selected node as follows. It returns instance of NameNodeMap interface present in org.w3c.dom.* package.
NamedNodeMap map=element.getAttributes();
- Now check whether selected node has given attribute or not.
node=map.getNamedItem(attribute);
- If attribute found then delete it as follows.
element.removeAttribute(attribute);
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
DeleteEmployeeAttribute.java
employee.xml
Download Project
Click here for more questions on DOM Parser.
Project Structure:
![]() |
Figure 2 |
Java Code:
employee.xml
1234567891011121314151617<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employees>
<Employee id="1" language="hindi">
<name>Rohit</name>
<gender>male</gender>
<age>25</age>
<role>Programmer</role>
</Employee>
<Employee id="2" language="english">
<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; | |
} | |
} |
DeleteEmployeeAttribute.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.NamedNodeMap; | |
import org.w3c.dom.Node; | |
import org.w3c.dom.NodeList; | |
import org.xml.sax.SAXException; | |
public class DeleteEmployeeAttribute { | |
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 attribute name : "); | |
String attribute=input.readLine(); | |
boolean result=deleteEmployeeAttributeFromXml(document,id,attribute); | |
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 attribute has been deleted successfully."); | |
} | |
else | |
{ | |
System.out.println("Either employee id or attribute name is wrong."); | |
} | |
} | |
finally | |
{ | |
if(input!=null){ | |
input.close(); | |
} | |
} | |
} | |
private static boolean deleteEmployeeAttributeFromXml(Document document, int id, String attribute) { | |
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))) | |
{ | |
NamedNodeMap map=element.getAttributes(); | |
node=map.getNamedItem(attribute); | |
if(node!=null) | |
{ | |
element.removeAttribute(attribute); | |
result=true; | |
break; | |
} | |
} | |
} | |
} | |
return result; | |
} | |
} |
Output:
![]() |
Figure 3 |
employee.xml
12345678910111213141516<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employees>
<Employee id="1" language="hindi">
<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>
Here you can see that attribute language="english" 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
https://docs.oracle.com/javase/7/docs/api/javax/xml/transform/Transformer.html
https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/NamedNodeMap.html
https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/NamedNodeMap.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 attribute of given node in XML file using DOM parser in Java?
Reviewed by Rohit Agarwal
on
10/10/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.