An (x)Path out of the darkness…

โ€”

by

in

Read on and see the beauty that is a good [[XML]] parser in [[Flash]].

Well, it goes to show you how things can change in just a few hours. Remember
my Flash XML
parsing
issue? Well, I did some more poking around and I found out that the
folks who built [[XML]] realized that getting at specific data in it sucks. They
built something called [[XPath]] which you can sort of think of as a analog to
[[wp:SQL]] for a parsed XML tree.

Anyway, below you will find a sample XML file, a snippet of code to parse
that puppy and some reference links. If you have any questions [[let me know]].

Sample XML input

<?xml version=”1.0″ ?>
<items>
    <item>
        <title>Welcome to the Tutorials</title>
        <weight>1</weight>
        <url>/content/sections/tutorials/article.php?article_id=16</url>
        <target>main_content</target>
    </item>
    <item>
        <title>article 15</title>
        <weight>25</weight>
        <url>/content/sections/tutorials/article.php?article_id=30</url>
        <target>main_content</target>
    </item>
</items>

A function to parse that XML tree

_global.parseMenu = function() {
    var titlePath:String = “/items/item/title”;
    var urlPath:String = “/items/item/url”;
    var menuTitles = mx.xpath.XPathAPI.selectNodeList(_global.menuItems_xml.firstChild, “/items/item/title”);
    var menuURLs = mx.xpath.XPathAPI.selectNodeList(_global.menuItems_xml.firstChild, “/items/item/url”);
    var menuTargets = mx.xpath.XPathAPI.selectNodeList(_global.menuItems_xml.firstChild, “/items/item/target”);
    var menuWeights = mx.xpath.XPathAPI.selectNodeList(_global.menuItems_xml.firstChild, “/items/item/weight”);

    for (var i = 0; i < menuTitles.length; i++) {
        // trace( “-_-_–_-_–_-_-> ” + i );
        _global.menuItems[i] = new Object;
        _global.menuItems[i].title = menuTitles[i].firstChild.nodeValue;
        _global.menuItems[i].url = menuURLs[i].firstChild.nodeValue;
        _global.menuItems[i].target = menuTargets[i].firstChild.nodeValue;
        _global.menuItems[i].weight = menuWeights[i].firstChild.nodeValue;

        // trace(_global.menuItems[i].title);
        // trace(_global.menuItems[i].url);
        // trace(_global.menuItems[i].target);
        // trace(_global.menuItems[i].weight);
    }
}

Reference links