From XML to XPath via Sax

The past week has been interesting, with breakneck speed in getting the initial DOM XML parsing working then when coming to selectively choosing information and needing XPath to query the XML file, it becomes a different kettle of fish. 

Installed with a sense of confidence from earlier XML success, it rapidly became apparent that the OSM data model wasn’t going to be compatible with a basic DOM parser, so moving onto XPath yesterday was a frank nightmare, with nothing going right, then in true fashion in 5 minutes I was up and compiling within 5 minutes of starting this morning using a SAX parser instead of my DOcument Model. 

The problem now is moving onto making the OSM data model fit with the XPath query language, possibly doing XLST transformations or at worst placing the data in a temporary SQL database and then pulling the data out then, time is of the essence!

For those interested here is the code to query XPath in Java…


import org.w3c.dom.*;

import org.xml.sax.SAXException;

import javax.xml.parsers.*;

import javax.xml.xpath.*;

public class XPathExample {

  public static void main(String[] args)  throws ParserConfigurationException, SAXException,  

          IOException, XPathExpressionException {

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();


    DocumentBuilder builder = domFactory.newDocumentBuilder();

    Document doc = builder.parse(/*Name of XML Document*/);

    XPathFactory factory = XPathFactory.newInstance();

    XPath xpath = factory.newXPath();

    XPathExpression expr = xpath.compile(/*XPATH QUERY HERE*/);


    Object result = expr.evaluate(doc, XPathConstants.NODESET);

    NodeList nodes = (NodeList) result;

    for (int i = 0; i < nodes.getLength(); i++) {






Author: Mark Iliffe

Traveller, Programmer, Geospatialist and Motorcyclist

3 thoughts on “From XML to XPath via Sax”

  1. recommended to add this lines to avoid refereneces to other files that may be not exist:
    builder.setEntityResolver(new EntityResolver(){
    public InputSource resolveEntity(String arg0, String arg1)
    throws SAXException, IOException {
    return new InputSource(new StringReader(“”));


  2. How can we use XPath with SAX parser rather than DOM object? Is ther any API/library that can support SAX Xpath? Could you please suggest on this?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s