XPath makes XML parsing easy

I’ve been using XPath and XQuery to parse my XML documents as of late and, wow, does it ever make parsing easier. For instance, suppose I wanted to collect elements which had a bar attribute of “baz”. Using The Mind Electric‘s Electric XML without XPath support, I would have to do something like the following, assuming document is an instance of electric.xml.Document:

Elements fooElements = document.getElements( "foo" );
while( fooElements.hasMoreElements() )
{
    Element fooElement = fooElements.next();
    Element barAttribute = fooElement.getAttribute( "bar" );
    if( barAttribute != null && barAttribute.equals( "baz" ) )
    {
        // Handle the foo elements
    }
}

With XPath, this is reduced to one line:

Elements fooElements 
        = document.getElements( new XPath( "foo[@bar='baz']" ) );

Aside from the shorter code, another upside is that all optimisations are left to the XML library. The second way is at least as fast as the first, unless the underlying code is very poorly written, and is just as easy to maintain. A short comment removes any confusion to those new to XPath. Then again, the first piece of code wouldn’t be immediately obvious without the same comment.

The downside to having XPath available is the quest to express any request for XML elements in a single expression. While before I grudgingly accepted the non-XPath way of retrieving XML elements, I now find myself poring over the spec to find that one expression which will make my life easier.

Leave a Reply