HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions

Java XPath NamespaceContext – NameSpace Resolution Example

By Lokesh Gupta | Filed Under: XML

In this java example, we will learn XPath namespace resolution into an XML file using NamespaceContext which has namespace declarations and respective usages.

Namespace added XML file

I have created sample.xml file and put in on classpath.

<ns2:bookStore xmlns:ns2="http://bookstore.com/schemes">
	<ns2:book id="1">
		<ns2:name>Data Structure</ns2:name>
	</ns2:book>
	<ns2:book id="2">
		<ns2:name>Java Core</ns2:name>
	</ns2:book>
</ns2:bookStore>

Implement NamespaceContext to create namespace resolver

This namespace resolver can be used with any XML file where namespace definitions have been used. It searches for namespace declarations for any given namespace prefix – passed as parameter – inside XML document itself. So no need to create namespace mapping separately.

public class NamespaceResolver implements NamespaceContext 
{
	//Store the source document to search the namespaces
    private Document sourceDocument;

    public NamespaceResolver(Document document) {
        sourceDocument = document;
    }

    //The lookup for the namespace uris is delegated to the stored document.
    public String getNamespaceURI(String prefix) {
        if (prefix.equals(XMLConstants.DEFAULT_NS_PREFIX)) {
            return sourceDocument.lookupNamespaceURI(null);
        } else {
            return sourceDocument.lookupNamespaceURI(prefix);
        }
    }

    public String getPrefix(String namespaceURI) {
        return sourceDocument.lookupPrefix(namespaceURI);
    }

    @SuppressWarnings("rawtypes")
	public Iterator getPrefixes(String namespaceURI) {
        return null;
    }
}

Using NamespaceResolver and apply XPath

Now we are ready to apply xpath expression over XML file.

//Want to read all book names from XML
ArrayList<String> bookNames = new ArrayList<String>();

//Parse XML file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); 
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new FileInputStream(new File("sample.xml")));

//Get XPath expression
XPathFactory xpathfactory = XPathFactory.newInstance();
XPath xpath = xpathfactory.newXPath();
xpath.setNamespaceContext(new NamespaceResolver(doc));
XPathExpression expr = xpath.compile("//ns2:bookStore/ns2:book/ns2:name/text()"); 

//Search XPath expression
Object result = expr.evaluate(doc, XPathConstants.NODESET);

//Iterate over results and fetch book names
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
	bookNames.add(nodes.item(i).getNodeValue());
}

//Verify book names
System.out.println(bookNames);

Output of above program is:

[Data Structure, Java Core]

Complete Source Code for XPath Namespace Resolution

This is the complete sourcecode of above example.

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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;


public class Main 
{
	public static void main(String[] args) throws Exception 
	{
		//Want to read all book names from XML
		ArrayList<String> bookNames = new ArrayList<String>();
		
		//Parse XML file
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true); 
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new FileInputStream(new File("sample.xml")));
        
        //Get XPath expression
        XPathFactory xpathfactory = XPathFactory.newInstance();
        XPath xpath = xpathfactory.newXPath();
        xpath.setNamespaceContext(new NamespaceResolver(doc));
        XPathExpression expr = xpath.compile("//ns2:bookStore/ns2:book/ns2:name/text()"); 
        
        //Search XPath expression
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        
        //Iterate over results and fetch book names
        NodeList nodes = (NodeList) result;
        for (int i = 0; i < nodes.getLength(); i++) {
        	bookNames.add(nodes.item(i).getNodeValue());
        }
        
        //Verify book names
        System.out.println(bookNames);
	}
}
class NamespaceResolver implements NamespaceContext 
{
	//Store the source document to search the namespaces
    private Document sourceDocument;

    public NamespaceResolver(Document document) {
        sourceDocument = document;
    }

    //The lookup for the namespace uris is delegated to the stored document.
    public String getNamespaceURI(String prefix) {
        if (prefix.equals(XMLConstants.DEFAULT_NS_PREFIX)) {
            return sourceDocument.lookupNamespaceURI(null);
        } else {
            return sourceDocument.lookupNamespaceURI(prefix);
        }
    }

    public String getPrefix(String namespaceURI) {
        return sourceDocument.lookupPrefix(namespaceURI);
    }

    @SuppressWarnings("rawtypes")
	public Iterator getPrefixes(String namespaceURI) {
        return null;
    }
}

Let me know of your questions in comments section.

Happy Learning !!

Reference: http://www.ibm.com/developerworks/library/x-nmspccontext/

About Lokesh Gupta

Founded HowToDoInJava.com in late 2012. I love computers, programming and solving problems everyday. A family guy with fun loving nature. You can find me on Facebook, Twitter and Google Plus.

Feedback, Discussion and Comments

  1. Peter Mundt

    July 26, 2018

    Good example, excellent explained! This example helped me a lot! Thanks!

    Reply

Ask Questions & Share Feedback Cancel reply

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

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Help me fight spammers. Solve this simple math. *

Search Tutorials

  • Email
  • Facebook
  • RSS
  • Twitter

Java XML Tutorial

  • Java – Read XML DOM Parser
  • Java – Read XML SAX Parser
  • Java – Read XML JDOM2 Parser
  • Java – Read XML StAX Parser
  • Java – DOM vs SAX Parser
  • Java – Convert XML to Properties
  • Java – Convert Properties to XML
  • Java – Convert String to XML
  • Java – Convert XML to String
  • Java – XPath Tutorial
  • Java – Evaluate XPath on DOM
  • Java – Evaluate XPath on String
  • Java – XPath Examples
  • Java – XPath NamespaceContext
  • Java – Get Attribute using XPath
  • Java – XPath Attribute Examples
  • Java – Check if XML tag exists?

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Java Collections
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap