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:
import memorphic.xpath.parser.*;
import memorphic.xpath.XPathQuery;
To execute a query just declare an XPathQuery object and call the exec() method which returns an ‘XMLList’ of matches:
// Get a list of the 'News' Items..
var myQuery:XPathQuery =
new XPathQuery("/Content/ContentData/ContentItemList[@name='news']");
// execute the statement on the XML object and get the result
var result:XMLList = myQuery.exec(_xml);
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:
memorphic\xpath\model\QueryRoot.as
we changed:
contextNode.appendChild(xmlRoot.copy());
to:
contextNode.appendChild(xmlRoot);
With no ill effects (yet!).