Friday, May 09, 2008

XPath: baby steps


As I'm learning about XPath, I want to do something like "find all Traveller nodes for which the DepartFrom node is "Bton". The XPath would be something like:

.//Traveller//DepartFrom[. = "Bton"]

But this does not return the Traveller nodes, this returns the DepartFrom nodes. Now, if I knew for certain that Traveller is the direct ancestor of DepartFrom, I could do this:

.//Traveller/DepartFrom[. = "Bton"]/..

Or if Traveller is the grandparent, do this:

.//Traveller//DepartFrom[. = "Bton"]/../..

etc... but what if I know Traveller is up there somewhere, but not exactly how many levels up? I'm not sure XPath can do that, at least not in one search. I can do it with multiple searches, first locating all of the Traveller nodes and then doing an XPath search on each one individually to sift out the ones I really want.

The // operator is great for descending down some arbitrary number of levels, but there doesn't seem to be a way to do the inverse. Alternatively, XPath could use some kind of qualifier that says "return the head node of this XPath rather than the tail node." It's kind of frustrating. Imagine if a regular expression only returned the last character of the matching string!

0 comments: