Many of the situations we might encounter a situation where we need to read the xml document with namespaces in it. The example mentioned in below link will only address if namepspace is not specified in loaded XML document

Java XPath Example

Following example will show us how to read XML document qualified with namespace using XPath.

1. XML document

<?xml version="1.0" encoding="UTF-8"?>
<college xmlns="http://com.codesimplify.java/xpath/">
	<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>

2. Load XML document

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

3. Read XML document

below code snippet will show us 2 common usages of Xpath.

  • Filter by Attribute
  • Filter by Attribute and Node value
	XPathFactory factory = XPathFactory.newInstance();
	XPath xpath = factory.newXPath();
	// Filter by Attribute
	XPathExpression expr = xpath.compile("//*[local-name()='department'][@*[local-name() = 'name' and .='science']]/*/*[local-name()='firstName']");

	/** Below line is sufficient if there is no namespace associated to the document.
	 *  XPathExpression expr = xpath.compile("/college/department[@name = 'science']/student/firstName");
	 */

	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("//*[local-name()='department'][@*[local-name() = 'name' and .='science']]/*/*[local-name()='rollNum' and .='2']/../*[local-name()='firstName']");
	/** Below line is sufficient if there is no namespace associated to the document.
	 *  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());		        
	}

4. Output

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

5. Complete 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_ns_example.xml");		
			
		    // Read first of students in science department
			XPathFactory factory = XPathFactory.newInstance();
		    XPath xpath = factory.newXPath();
		    // Filter by Attribute
		    XPathExpression expr = xpath.compile("//*[local-name()='department'][@*[local-name() = 'name' and .='science']]/*/*[local-name()='firstName']");
		   
		    /** Below line is sufficient if there is no namespace associated to the document.
		     *  XPathExpression expr = xpath.compile("/college/department[@name = 'science']/student/firstName");
		     */
		    
		    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("//*[local-name()='department'][@*[local-name() = 'name' and .='science']]/*/*[local-name()='rollNum' and .='2']/../*[local-name()='firstName']");
		    /** Below line is sufficient if there is no namespace associated to the document.
		     *  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 Ignore Namespace Example

Leave a Reply

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