XPath with Adobe ActionScript 3

While working on a custom XML data-driven content management system in ActionScript 3, we wanted to have our XML content meta-data reference the actual XML content data by means of XPath expressions – hence we needed some half decent XPath support within AS3.

AS3 has quite good XML support, however its support for XPath expressions and queries is not much to write home about at all!  So instead, we have been using memorphic’s open source XPath implementation with much success.  It is easy to install & use, and it does a good job at implementing the majority of the XPath standard.

To use it, first download it and extract the src\memorphic folder to somewhere on your path.  Then import the XPath support to your AS3 code as follows:

To execute a query just declare an XPathQuery object and call the exec() method which returns an ‘XMLList’ of matches:

Quite refreshingly straightforward really.

One thing to look out for, and which caused a lot of head-scratching for a while is that memorphic executes the XPath expression against a _copy_ of the provided XML tree, and the returned nodes belong to that tree and not the original – hence if you later modify any of these nodes, it is the copy that is modified and not the original XML tree, this was not really spelled out in any of the documentation.

For us, it was very important that this was not the case, so we got around the problem by just modifying the query code as follows:

within the definition of the function execRoot() in the file:

we changed:

to:

With no ill effects (yet!).

1 reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *