How to do search in XML file using DOM Parser in Java?

Problem Description:

Suppose we have following XML file as an example.

   <Employee id="1">
   </Employee >
  <Employee id="2">
   <Employee id="3">

Here requirement is to search child node Employee whose id is 2. Similarly user can search any child node. 


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* package.

File file = new File(XML_file_location);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);

XML Search using Java DOM Parser
Figure 1

2) 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");

3) 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.
          Node node = list.item(i);
  • Check whether this node is Element node or not?
          if (node.getNodeType() == Node.ELEMENT_NODE) { }
  • If it is an Element node then typecast it and get its data (attributes and properties).
          Element element = (Element) node;
  • Get its id as follows.
          String id=element.getAttribute("id");
  • Compare this id with id of Employee that you want to search.
         if (String.valueOf(id).equals(element.getAttribute("id"))) {}
  • Now get all employee properties as follows.
           String value = element.getElementsByTagName(property_name).item(0).getTextContent();

Software Required:

  1. Java
  2. Eclipse
  3. 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.

Project Structure:

Java XML DOM Parser Structure part 3
Figure 2

Java Code:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employee id="1">
<Employee id="2">


About Author:

I am simple guy with lot of ambitions. My main motive is to share whatever knowledge I have related to programming. With me you can easily learn how to solve any programming problem in Java.You can connect with me on social networking sites also.

Let's Get Connected: Linkedin | Facebook |

How to do search in XML file using DOM Parser in Java? How to do search in XML file using DOM Parser in Java? Reviewed by Rohit Agarwal on 10/04/2017 Rating: 5

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.

Powered by Blogger.