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 :
Let’s say you have the XML file containing this :
<code> <news> <swf_file>C0201.swf</swf_file> <options> <format>html</format> <textcolour>red</textcolour> </options> <stories> <story> <heading>PLUG-IN-O-VISION IS REVEALED</heading> <summary>GEE-WHIZZ Plug-in's all new website has launched!</summary> </story> <story> <heading>FLASH FORWARD in Texas SPEAKER SHOCKER!</heading> <summary>Plug-in's technical director presents 3D in Flash at FlashForward Texas.</summary> </story> <story> <heading>Plug-in Media Directs Sony Video Nasty!</heading> <summary>Sony called upon Plug-in Media to produce EyeToy Next Generation promotional film.</summary> </story> </stories> </news> </code>
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
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.