Query XML Document

Java StAX parser is a Java API which is used to parse XML documents and query the necessary information. This API is event based and hence we need not load entire XML document to query it. As the parser identifies each event, the corresponding action is performed only when the client program implements the event.

In this chapter, we are going to see how to query an XML document to get necessary information.

Query XML Using Java StAX Parser

Following are the steps we need to follow to query an XML document using Java StAX parser −

  • Step 1: Creating XMLInputFactory instance
  • Step 2: Reading the XML
  • Step 3: Parsing the XML
  • Step 4: Querying the Elements

Step 4: Querying the Elements

After following the first three steps, we have XMLEventReader to get events from the XML document. Using various events and by implementing them, we can query the XML document. Let us see how we can do this in detail.

Querying Elements by Text Content

We can get the text content in any element of an XML document by using getData().This method of Characters interface returns the character data of the current event in the form of a String. Using this method, we can query all the elements to find the required text content.

Example

The cars.xml file shown below has many carname elements with different text content. Let us query this file to find out if “Bentley 2” car is present.

<?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>

The following QueryTextContent.java program reads the cars.xml file using a FileReader object. When the CHARACTERS event type is encountered, the getData() method is used to get the text content. If that data is equal to “Bentley 2”, then we are updating the ‘found’ boolean variable. In the END_DOCUMENT event, we are printing it on the console.

importjava.io.FileReader;importjavax.xml.stream.XMLEventReader;importjavax.xml.stream.XMLInputFactory;importjavax.xml.stream.XMLStreamConstants;importjavax.xml.stream.events.Characters;importjavax.xml.stream.events.XMLEvent;publicclassQueryTextContent{publicstaticvoidmain(String args[]){try{//Creating XMLInputFactory instanceXMLInputFactory factory =XMLInputFactory.newInstance();//Reading the XMLFileReader fileReader =newFileReader("cars.xml");//Parsing the XMLXMLEventReader eventReader =
          factory.createXMLEventReader(fileReader);//Querying the XMLboolean found=false;while(eventReader.hasNext()){XMLEvent event = eventReader.nextEvent();if(event.getEventType()==XMLStreamConstants.CHARACTERS){Characters characters = event.asCharacters();String textContent = characters.getData();if(textContent.equals("Bentley 2"))
              	  found=true;}if(event.getEventType()==XMLStreamConstants.END_DOCUMENT){if(found)System.out.println("Bentley 2 car is found");elseSystem.out.println("Bentley 2 car is not found");}}}catch(Exception e){
		   e.printStackTrace();}}}

Output

Since, Bentley 2 car is present in cars.xml file, it prints that it is found.

Bentley 2 car is found

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

Querying Elements by Attributes

The getAttributeByName() method of an Element interface takes the QName object which is the qualified XML name of an attribute and returns the Attribute object. Further, the getValue() method of Attribute interface is used to get the value of the attribute in the form of a String.

Example 1

The cars.xml file that we have used in the previous example is parsed in the following QueryAttributes.java program to count the number of Bentley cars present in the XML file. A count variable is incremented each time the company attribute of the carname element is equal to Bentley.

importjava.io.FileReader;importjavax.xml.namespace.QName;importjavax.xml.stream.XMLEventReader;importjavax.xml.stream.XMLInputFactory;importjavax.xml.stream.XMLStreamConstants;importjavax.xml.stream.events.Attribute;importjavax.xml.stream.events.StartElement;importjavax.xml.stream.events.XMLEvent;publicclassQueryExample2{publicstaticvoidmain(String args[]){try{//Creating XMLInputFactory instanceXMLInputFactory factory =XMLInputFactory.newInstance();//Reading the XMLFileReader fileReader =newFileReader("cars.xml");//Parsing the XMLXMLEventReader eventReader =
           factory.createXMLEventReader(fileReader);//Querying the XML documentint count=0;while(eventReader.hasNext()){XMLEvent event = eventReader.nextEvent();if(event.getEventType()==XMLStreamConstants.START_ELEMENT){StartElement element=event.asStartElement();QName qname=newQName("company");Attribute attr=element.getAttributeByName(qname);if(attr!=null&& attr.getValue().equals("Bentley"))
                   count++;}}System.out.println("No.of Bentley cars found : "+ count);}catch(Exception e){
		   e.printStackTrace();}}}

The number of Bentley cars in the XML file are displayed.

No.of Bentley cars found : 3

Example 2

In this example, we are going to retrieve the information of a particular student based on their roll number. Here is the student.xml file we need to query −

<?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>

In the following QueryStudent.java program, we have checked for the events START_ELEMENT, CHARACTERS and END_ELEMENT and performed actions accordingly. when the roll number attribute is equal to 393, we are printing the entire information of the student.

importjava.io.FileReader;importjava.util.Iterator;importjavax.xml.stream.XMLEventReader;importjavax.xml.stream.XMLInputFactory;importjavax.xml.stream.XMLStreamConstants;importjavax.xml.stream.events.Attribute;importjavax.xml.stream.events.Characters;importjavax.xml.stream.events.EndElement;importjavax.xml.stream.events.StartElement;importjavax.xml.stream.events.XMLEvent;publicclassQueryStudent{publicstaticvoidmain(String[] args){boolean bFirstName =false;boolean bLastName =false;boolean bNickName =false;boolean bMarks =false;boolean isRequestRollNo =false;try{//Creating XMLInputFactory instanceXMLInputFactory factory =XMLInputFactory.newInstance();//Reading the XMLFileReader fileReader =newFileReader("student.xml");//Parsing the XMLXMLEventReader eventReader =
            factory.createXMLEventReader(fileReader);//Querying the XML String requestedRollNo ="393";while(eventReader.hasNext()){XMLEvent event = eventReader.nextEvent();switch(event.getEventType()){caseXMLStreamConstants.START_ELEMENT:StartElement startElement = event.asStartElement();String qName = startElement.getName().getLocalPart();if(qName.equalsIgnoreCase("student")){Iterator<Attribute> attributes = startElement.getAttributes();String rollNo = attributes.next().getValue();if(rollNo.equalsIgnoreCase(requestedRollNo)){System.out.println("Start Element : student");System.out.println("Roll No : "+ rollNo);
                     isRequestRollNo =true;}}elseif(qName.equalsIgnoreCase("firstname")){
                  bFirstName =true;}elseif(qName.equalsIgnoreCase("lastname")){
                  bLastName =true;}elseif(qName.equalsIgnoreCase("nickname")){
                  bNickName =true;}elseif(qName.equalsIgnoreCase("marks")){
                  bMarks =true;}break;caseXMLStreamConstants.CHARACTERS:Characters characters = event.asCharacters();if(bFirstName && isRequestRollNo){System.out.println("First Name: "+ characters.getData());
                  bFirstName =false;}if(bLastName && isRequestRollNo){System.out.println("Last Name: "+ characters.getData());
                  bLastName =false;}if(bNickName && isRequestRollNo){System.out.println("Nick Name: "+ characters.getData());
                  bNickName =false;}if(bMarks && isRequestRollNo){System.out.println("Marks: "+ characters.getData());
                  bMarks =false;}break;caseXMLStreamConstants.END_ELEMENT:EndElement endElement = event.asEndElement();if(endElement.getName().getLocalPart().equalsIgnoreCase("student")&& isRequestRollNo){System.out.println("End Element : student");System.out.println();
                  isRequestRollNo =false;}break;}}}catch(Exception e){
         e.printStackTrace();}}}

All the information of the student with roll number 393 is displayed.

Start Element : student
Roll No : 393
First Name: dinkar
Last Name: kad
Nick Name: dinkar
Marks: 85
End Element : student

Comments

Leave a Reply

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