views:

974

answers:

1

I'm looking for an efficient and reusable way to parse xml into an object in actionscript2. The xml structure itself might change so it's important that im able to parse the xml with out 'hard coding' specific nodes, etc.

I normally use As3 and wouldn't need something like this since the XML class is easy to drill down into. Below is AS3 pseudocode of what I'm 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 any help on this!

+1  A: 

i did not fully understand your pseudo code ... what happens to the Array values? seems to be simply discarded ... also, it seems not to be recursive ...

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

what would you map this to?

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

and then, what would this be?

<cart><item /><cart>

and what this?

<cart />

the problem is, that in the first case, you have an array, in the second a property, in the third nothing ... so you can't know, what cart.item will be ... even if you say, that single child nodes will be wrapped into an array, you could still have no entry, and thus cart.item is null ... not that as2 would complain if you access properties of null but still, this is quite uggly ...

e4x seems to be the best way to traverse XML objects from an ECMA world ... after a little thinking, i've put together a little (quite hacky) library: http://code.google.com/p/as24x/ you can find other libraries on google though, that support more features ... it's rather about syntax ...

hope this helps ;)

back2dos