In this tutorial, we will see how to read xml document using xpath.

Step 1) Following XML document will show us the students enrolled into each department in college.

<?xml version="1.0" encoding="UTF-8"?>
<college>
	<department name="arts">
		<student>
			<rollNum>1</rollNum>
			<firstName>John</firstName>
			<lastName>Smith</lastName>
		</student>
		<student>
			<rollNum>2</rollNum>
			<firstName>Venkat</firstName>
			<lastName>Gutta</lastName>
		</student>
	</department>
	<department name="science">
		<student>
			<rollNum>2</rollNum>
			<firstName>Venkat</firstName>
			<lastName>Gutta</lastName>
		</student>
		<student>
			<rollNum>3</rollNum>
			<firstName>Lisa</firstName>
			<lastName>Sorenson</lastName>
		</student>
	</department>
</college>

Step 2) Java code that loads XML document

Document doc = null;
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware(true);
DocumentBuilder builder=null;
	   	    
builder = docFactory.newDocumentBuilder();
doc = builder.parse(fileName);

Step 3) Java Xpath code that prints firstName of students in science department.

Following code sample shows

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
// Filter by Attribute
XPathExpression expr = xpath.compile("/college/department[@name = 'science']/student/firstName");
// Filter by Attribute
System.out.println("Filter by Attribute example code:");
NodeList result =(NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i=0; i<result.getLength();i++){		       
    System.out.println(result.item(i).getTextContent());		        
}
		    
// Filter by Attribute and node text
System.out.println("Filter by Attribute and node text example code:");
XPathExpression expr1 = xpath.compile("/college/department[@name = 'science']/student[rollNum = 2]/firstName");
		    
NodeList result1 =(NodeList) expr1.evaluate(doc, XPathConstants.NODESET);
for (int i=0; i<result1.getLength();i++){		       
	System.out.println(result1.item(i).getTextContent());		        
}

Step 4) Output

Filter by Attribute example code:
Venkat
Lisa
Filter by Attribute and node text example code:
Venkat

step 5) Full example code

package com.codesimplify.java.xpath;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XPathReaderExample {

	public static void main(String[] args) {
		
		try{
		    XPathReaderExample xpathExample=new XPathReaderExample();
			// Load XML document
		    Document doc=xpathExample.getXmlDocument("c:\\temp\\xml_xpath_example.xml");		
			
		    // Read first of students in science department
			XPathFactory factory = XPathFactory.newInstance();
		    XPath xpath = factory.newXPath();

		    XPathExpression expr = xpath.compile("/college/department[@name = 'science']/student/firstName");
		    // Filter by Attribute
		    System.out.println("Filter by Attribute example code:");
		    NodeList result =(NodeList) expr.evaluate(doc, XPathConstants.NODESET);
		    for (int i=0; i<result.getLength();i++){		       
		        System.out.println(result.item(i).getTextContent());		        
		    }
		    
		    // Filter by Attribute and node text
		    System.out.println("Filter by Attribute and node text example code:");
		    XPathExpression expr1 = xpath.compile("/college/department[@name = 'science']/student[rollNum = 2]/firstName");
		    
		    NodeList result1 =(NodeList) expr1.evaluate(doc, XPathConstants.NODESET);
		    for (int i=0; i<result1.getLength();i++){		       
		        System.out.println(result1.item(i).getTextContent());		        
		    }
		    
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	
	public Document getXmlDocument(String fileName) throws IOException,ParserConfigurationException,SAXException{
		Document doc = null;
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		docFactory.setNamespaceAware(true);
	    DocumentBuilder builder=null;
	   	    
	    builder = docFactory.newDocumentBuilder();
	    doc = builder.parse(fileName);
	    return doc;
	}	
	
	
}
Java Xpath example
Tagged on:     

One thought on “Java Xpath example

Leave a Reply

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