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:

cursor.toFirstChild();

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:

cursor.push();
...do some other navigation with the cursor....
cursor.pop();



get the text of an element:

cursor.getTextValue();

move to adjacent sibling:

cursor.toNextSibling();

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

No comments: