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:
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:
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.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.