Tuesday, July 12, 2011

XmlObject, XmlCursor and how to replace XPath with "hardcoded" queries

I was under the impression that a given XPath search was too slow, so I implemented the same search in Java.

It's not that difficult.
The main tools are:

a XmlCursor:

XmlCursor cursor = xmlObject.newCursor();

moving to first element inside a node:


moving to a child identified by its QName:

static QName qnameLongNames = new QName("http://acme.com", "LongNames");
boolean found1 = cursor.toChild(qnameLongNames);

eventually using an index if there are multiple elements with same QName:

int count = 0;
boolean found1 = cursor.toChild(qnameLongNames, count);

saving a cursor for later use:

...do some other navigation with the cursor....

get the text of an element:


move to adjacent sibling:


With this, you can achieve a lot, and at amazing speed.

No comments: