XML parsing in Actionscript made easy with Flash XPath – who knew?

Every now and again you find something in Flash that you can’t believe you’ve ever lived with out. Thank goodness Tom Kennett (one of the FlashCodersBrighton) showed me the FlashMX XPathAPI. Never will I have to custom write an XML parser again!

To use the XPathAPI, first you import the library :

import mx.xpath.*;

Let’s say you have the XML file containing this :

         GEE-WHIZZ Plug-in's all new website
         has launched!
         Plug-in's technical director presents 3D
         in Flash at FlashForward Texas.
         Plug-in Media Directs Sony Video Nasty!
         Sony called upon Plug-in Media to produce EyeToy
         Next Generation promotional film.

First of all we need to extract the main node out of the XML object:

var mainnode : XMLNode = myXMLObject.firstChild;

Now using XPathAPI we can get any subsequent node value easily! To get the contents of the tag, we use:

textcolour = XPathAPI.selectSingleNode(mainnode, "news/options/textcolour").firstChild.nodeValue;

You can see there that we can access nodes within the XML structure in the same way that we would access files in a directory tree : “news/options/textcolour”. As the selectSingleNode function returns (unsurprisingly) an XMLNode, we get the contents of that node using .firstChild.nodeValue.

But an even better feature of the XPathAPI is the selectNodeList() method which returns an array of nodes!

For a fuller explanation, check out this informative post at Last Actionscript Hero.

9 replies on “XML parsing in Actionscript made easy with Flash XPath – who knew?”

Hey Seb
I had to give up Macromedia’s xpath and use the xfactorstudio instead for a simple, but serious, reason: You can’t go “up” one level on the xml tree with macromedia implementation;
for example, if you want to go “down”, you use /level/level, and up /level/../../ – the classic slash/dot syntax. If you want to select the parent node of all nodes that contain a certain keyword, you’re in trouble. And that not a usual query…

under 512Kb XML document, it’s often best (e.g. if you’re doing multiple lookups to the file) to parse the whole file to convert it to an AS Object.

There’s several implementations of this process, I posted an AS1 prototype a few years ago on //

If you like I’ll post you up an AS2.0 event driven class.

Using this method, the lookup in your example would be…

textcolour =;

Note: Multiple nodes would be parsed as arrays… eg.[0].heading._value == “PLUG-IN-O-VISION IS REVEALED”

Thanks Shane, it seems like there are a few options here, will def be exploring your code next time I need an XML parser!



Comments are closed.