Recursive XML parsing in ActionScript 2

I am looking for an efficient and reusable way to parse xml in an object in actionscript2. The structure of the xml itself can change, so it is important that they can parse the xml without certain hardcoding nodes, etc.

I usually use As3 and don't need something like this as the XML class is easy to deploy. Below is AS3 pseudocode of what I am trying to accomplish.

    public function XmlObject(myXmlObject:XML,_node:String):Object
    {
        var xmlObj:Object=new Object();

        for(var node:uint=0;node<myXmlObject[_node].children().length();node++)
        {
            var attributesList:XMLList=myXmlObject[_node].children()[node].attributes();
            var nodeName:String=myXmlObject[_node].children()[node].name(); 

            switch(attributesList.length()>1)
            {
                //////////////////////
                case false:
                //////////////////////
                {
                  for each(var attribute:XML in attributesList)
                  { 
                    xmlObj[nodeName]=attribute;
                  } 
                break;


                //////////////////////
                case true:
                //////////////////////
                var values:Array=[];
                for each(attribute in attributesList)
                {
                    values.push(attribute);
                    xmlObj[nodeName][String(attribute.name())]=attribute;
                }   
                break;
            }
        }
    return xmlObj;
    }

      

Thanks in advance for your help!

+1


a source to share


1 answer


I didn't quite understand your pseudocode ... what's going on with the array values

? seems to just be discarded ... also doesn't seem to recursive ...

the problem is that the semantics of XML and ECMA objects are different ...

what could you match this to?

<cart><item /><item /></cart>

      

and then what would it be?

<cart><item /><cart>

      

and what is it?



<cart />

      

the problem is that in the first case you have an array, in the second you have a property, in the third nothing ... so you cannot know what cart.item

will happen ... even if you say that single child nodes will be wrapped in an array, you you may still not have an entry, and thus there cart.item

is null

... not that as2 will complain about property access null

, but still pretty uggly ...

e4x seems to be the best way to move XML objects out of the ECMA world ... after a little thought I put together a small (rather hacky) library: http://code.google.com/p/as24x/ you can find other libraries at google, though, which support more features ... it's more about syntax ...

hope this helps;)

Greetz

back2dos

+1


a source







All Articles