Query XML Document


Java DOM4J Parser – Query XML Document


”;


Java DOM4J parser is an open source Java library to parse and query the necessary information from XML documents. We can query XML documents using the methods of Document and Element interfaces of DOM4J. The elements() method retrieves all the elements of root element. Using attributeValue() method, we can query the attributes of elements.

Query XML Using Java DOM4J Parser

Following are the steps used while querying a document using Java DOM4J Parser −

  • Step 1: Creating SAXReader object
  • Step 2: Reading the XML file
  • Step 3: Parsing the XML
  • Step 4: Extracting the root
  • Step 5: Querying the Document

Refer Parse XML Document chapter of this section for first four steps.

Step 5: Querying the Document

After extracting the root in step 4, we can query the child elements using the root element. Now we are going to query XML documents by querying their elements and by querying their attributes.

Querying Elements

To get elements with specific name, we can use elements() method of Element interface and pass the name of the element we need to obtain as a parameter in the form of a string. This method returns the list of elements with the same name.

The getData() method of Element interface returns the text data in the form of a String. To query an element based on its text content, we can use this method with equals() method for comparison.

Example

Following is the cars.xml file we need to query −

<?xml version = "1.0"?>
<cars>
      <carname company="Ferarri" >Ferarri 101</carname>
      <carname company="Lamborgini">Lamborgini 001</carname>
      <carname company="Lamborgini">Lamborgini 002</carname>
      <carname company="Lamborgini">Lamborgini 003</carname>
      <carname company="Bentley">Bentley 1</carname>
      <carname company="Bentley">Bentley 2</carname>
      <carname company="Bentley">Bentley 3</carname>
</cars>

Using the QueryElements.java program, we are querying the cars.xml file to find if there is “Bentley 2″ car available. We get all the ”carname” elements from elements() method and comparing the text content using getData() method.

import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class QueryElements {
   public static void main(String[] args) {
      try {
    	  
    	 //Creating SAXReader
         SAXReader reader = new SAXReader();
         
    	 //Reading the XML file
         File inputFile = new File("cars.xml");
         
         //Parsing the XML
         Document document = reader.read(inputFile);

         //Extracting the root
         Element RootElement = document.getRootElement();

         List<Element> elements = RootElement.elements("carname");
         boolean found = false;
         
         //Iterating over the List
         for (Element ele : elements) {
        	    if(ele.getData().equals("Bentley 2")) {
        	    	found = true;      	    	
        	    }
         }
         if(found) {
        	 System.out.println("Bentley 2 car is found");
         }
         else {
        	 System.out.println("Bentley 2 car is not found");
         }	 
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Output

The output window displays that ”Bentley 2” car is found in the document.

Bentley 2 car is found

Querying Attributes

We can query for a specific attribute of an Element interface by using the attributeValue() method. We can pass a string value which is the name of the attribute as an argument to this method and it returns the value as a string.

Example 1

The following QueryAttributes.java program gets the list of ”carname” elements and checks if the value of its attribute ”company” equals to ”Bentley” and the integer variable ”count” is incremented.

import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class QueryAttributes {
   public static void main(String[] args) {
      try {
    	  
    	//Creating SAXReader
          SAXReader reader = new SAXReader();
          
     	 //Reading the XML file
          File inputFile = new File("cars.xml");
          
          //Parsing the XML
          Document document = reader.read(inputFile);

          //Extracting the root
          Element RootElement = document.getRootElement();
          
         List<Element> elements = RootElement.elements("carname");
         int count = 0;
         
         for (Element ele : elements) {
        	    if(ele.attributeValue("company").equals("Bentley")) 
        	    	count++;
         }
        	 System.out.println("No of Bentley cars found: " + count);	 
      } catch (DocumentException e) {
         e.printStackTrace();
      }
   }
}

Output

The output window displays the number of Bentley cars found in the document.

No of Bentley cars found: 3

Example 2

Consider the following studentData.xml file with three student elements inside the root element ”class”. Let us now try to print the information about the student with roll number 493.

<?xml version = "1.0"?>
<class>
   <student rollno = "393">
      <firstname>dinkar</firstname>
      <lastname>kad</lastname>
      <nickname>dinkar</nickname>
      <marks>85</marks>
   </student>
   
   <student rollno = "493">
      <firstname>Vaneet</firstname>
      <lastname>Gupta</lastname>
      <nickname>vinni</nickname>
      <marks>95</marks>
   </student>
   
   <student rollno = "593">
      <firstname>jasvir</firstname>
      <lastname>singn</lastname>
      <nickname>jazz</nickname>
      <marks>90</marks>
   </student>
</class>

The following QueryStudent.java program gets all the elements of the root element ”class”. It the compares the value of roll number attribute with ”493”. If it matches, it prints all the student details using elementText() method.

import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class QueryStudent {
   public static void main(String[] args) {
      try {
    	  
         //Creating SAXReader
         SAXReader reader = new SAXReader();
          
     	 //Reading the XML file
         File inputFile = new File("studentData.txt");
          
         //Parsing the XML
         Document document = reader.read(inputFile);

         //Extracting the root
         Element RootElement = document.getRootElement();
         System.out.println("Root element :" + RootElement.getName());
         
         List<Element> elements = RootElement.elements();
         System.out.println("----------------------------");        
         for (Element ele : elements) {
        	 if(ele.attributeValue("rollno").equals("493")) {
             System.out.println("nCurrent Element :"
                + ele.getName());
             System.out.println("Student roll no : " 
                + ele.attributeValue("rollno") );
             System.out.println("First Name : "
                + ele.elementText("firstname"));
             System.out.println("Last Name : "
                + ele.elementText("lastname"));
             System.out.println("First Name : "
                + ele.elementText("nickname"));
             System.out.println("Marks : "
                + ele.elementText("marks"));
        	 }
         }
        	 
      } catch (DocumentException e) {
         e.printStackTrace();
      }
   }
}

Output

All the details of the student with roll number 493 are displayed.

Root element :class
----------------------------

Current Element :student
Student roll no : 493
First Name : Vaneet
Last Name : Gupta
First Name : vinni
Marks : 95

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *