Showcase and discover digital art at yex

Follow Design Stacks

Subscribe to our free newsletter to get all our latest tutorials and articles delivered directly to your inbox!

Using XPath in Flash MX 2004

Using XPath in Flash MX 2004

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.<method_name>”.

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.

  1. import mx.xpath.XPathAPI;
  2. var rssfeed_xml = new XML();
  3. rssfeed_xml.ignoreWhite = true;
  4. rssfeed_xml.load("");
  5. rssfeed_xml.onLoad = function(success) {
  6.     if (success) {
  7.         var titlePath:String = "/rdf:RDF/item/title";
  8.         title_array = mx.xpath.XPathAPI.selectNodeList(this.firstChild, titlePath);
  9.         for (var i = 0; i<title_array.length; i++) {
  10.             trace(title_array[i].firstChild.nodeValue);
  11.         }
  12.     } else {
  13.         trace("error loading XML");
  14.     }
  15. };

Special thanks to Nate Weiss for helping me debug this. More information about XPath and using it within your Flash applications can be found in Nate’s latest book Flash MX Professional 2004 for Server Geeks.