Using XPath with Flash

A blog post of mine from yesteryear, but the issue came up recently (and the class is undocumented) so I thought I’d reblog it.

Flash MX 2004 introduced the XPathAPI class which allows you to do simple XPath searches within Flash. This can be very useful for searching XML packets based on node names and attribute values.

In order to use XPath searches within Flash you first need to include the XPathAPI class into your Flash library by including the DataBindingClass if it hasn’t been included already. If you’ve already set up bindings this class may have been included automatically, otherwise you’ll need to select the class from the common libraries by selecting Window > Other Panels > Common Libraries > Classes. From the Classes.fla library panel you can simply drag a copy of the DataBindingClasses component into your current Flash document’s library. Now you can import the class by typing “import mx.xpath.XPathAPI;” or by using the classes fully qualified name when accessing its methods by prefixing the class’ methods with mx.xpath.XPathAPI.”.

The XPath class has two methods; selectNodeList and selectSingleNode. The selectNodeList method returns an array of XML nodes matching the XPath expression, whereas the selectSingleNode returns only the first matching node.

You can see an example of the XPath API in ActionScript below, before you can test the movie you have to make sre that you have a copy of the DataBindingClasses component in your movie’s library by dragging it from Common Libraries > Classes into your current Flash movie’s library.

import mx.xpath.XPathAPI;
var rssfeed_xml:XML = new XML();
rssfeed_xml.ignoreWhite = true;
rssfeed_xml.load("http://www.markme.com/dehaan/index.rdf");
rssfeed_xml.onLoad = function(success:Boolean) {
  if (success) {
    var titlePath:String = "/rdf:RDF/item/title";
    var title_array:Array = XPathAPI.selectNodeList(this.firstChild, titlePath);
    for (var i = 0; i<title_array.length; i++) {
      trace(title_array[i].firstChild.nodeValue);
    }
  } else {
    trace("error loading XML");
  }
};

If you want more info on this class, check out Nate Weiss’ book here.