I’ve been interested in XPath lately. I am investigating using XPath to query ‘Sloppy’ HTML documents instead of XML documents for the purpose of writing web tests. I’ve been using a CSS like syntax cobbled together with nasty regular expressions that don’t work in all cases. For example:
$this->assertTextInElement('div.Status', 'The Category has been added to the database.');
I’ve found that there is a certain synergy between the tests and the CSS syntax. The things that you want to test also tend to be the things that you want to style. I’m not sure that the XPath syntax will be as well suited to this purpose. On the other hand, XPath is certainly more available and more capable.
So today, as a learning exercise, I hacked together a toy interpreter for XPath expressions in native PHP. Mostly to familiarize myself with the Specification. (Using time I probably should have used for something else, I might add).
It uses the HTML parser from WACT, which is tolerant of errors and not as restrictive as an XML parser. It builds a simple DOM. Following the HTML convention, it auto closes open tags, allowing stuff like this:
<ul> <li>item </ul>
Its extremely limited. It only supports location paths. It only supports root, element, and text nodes. It only supports the child, descendant-or-self, self, descendant, parent, ancestor, and ancestor-or-self axis. It doesn’t support predicate syntax. It supports the *, text(), node() and name node tests.
My test cases and examples are based on these excellent examples.
Its not much, but here it is:
My next step is to familiarize myself with the other XPath options under PHP.
I might experiment with a CSS Selector evaluator using the same simple DOM.
Anyway, its very late now and I’m going to bed.
Interesting idea, but I find this probably solves the original problem better:
http://dean.edwards.name/my/#cssQuery.js
Excellent! Thanks for sharing, we’ve been considering using XPath for our software, but if you’re finding it limited we may look into a custom development.
Danke!
-Ryan