Home  XML introduction

Search this site:
Threads Database Profiling Regular expressions Random numbers Compression Exceptions C Equivalents in Java
 Got a question about Java? Java discussion forum

XML parsing in Java with XPath (ctd)

Having now introduced the concepts of XML and XPath, we'll look at the standard Java API for reading an XML document using XPath. Two APIs are actually involved: the DOM or Document Object Model API, which gets the contents of an XML file into an object representation in memory, and the XPath API itself, which works on DOM objects. Both APIs are somewhat clumsy, but of the various clumsy options available, they're still generally the most practical.

Getting the DOM representation

The code to get the DOM representation looks as follows. It ultimately leaves us with a Document object:

import javax.xml.parsers.*;
import org.w3c.dom.*;

File xmlFile = ...
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xmlFile);

Evaluating an XPath query

The syntax for evaluating an XPath query in Java is a little bit topsy-turvy: we create an XPath object, via which we then evaluate an expression. The code looks like this:

import javax.xml.xpath.*;

Document doc = ... // as above
String exp = "/configuration/maxConnections/text()";
XPath xp = XPathFactory.newInstance().newXPath();
String maxConnsStr = xp.evaluate(exp, doc);

The XPath.evaluate() method usually gives us a string, but it's easy enough to extract an integer from this string, for example:

int maxConns = Integer.parseInt(maxConnsStr);


On the next page, we look at a performance issue that occurs when using the XPath API from an applet, and suggest a slightly clumsy workaround to this problem.

 Did this article answer your question? If not, visit the new Javamex discussion forums to ask your question.

Unless otherwise stated, the Java programming articles and tutorials on this site are written by Neil Coffey. Suggestions are always welcome if you wish to suggest topics for Java tutorials or programming articles, or if you simply have a programming question that you would like to see answered on this site. Most topics will be considered. But in particular, the site aims to provide tutorials and information on topics that aren't well covered elsewhere, or on Java performance information that is poorly described or understood. Suggestions may be made via the Javamex blog (see the site's front page for details).
Copyright © Javamex UK 2009. All rights reserved.