arraycollection with repeated nodes
In the resultHandler of an HTTPService call, I have assigned a repeating node to an arrayCollection. Inside that repeating node are other nodes that sometimes repeat and sometimes do not. For instance, here the option node repeats inside options.
<response>
<options>
<option> <var1> part1 </var1> <var2> part2 </var2> </option>
<option> <var1> part1 </var1> <var2> part2 </var2> </option>
</options>
<options>....
</response>
And sometimes it does not repeat, like this.
<response>
<options>
<option> <var1> part1 </var1> <var2> part2 </var2> </option>
</options>
<options>....
</response>
I am running into actionscript errors in my for loop. How do I account for both cases?
Here is my for loop assigning objects to value objects:
protected function xml_resultHandler(event:ResultEvent):void
{
var data:ArrayCollection = xml.lastResult.response.option;
var valueobjects:valueObject;
for each (var characteristic:Object in data)
{
valueobject = new valueobject;
valueobject.var1 = characteristic.option[0].var1;
valueobject.var2 = characteristic.option.var2;
datamodel.addItem(valueobject);
开发者_开发百科 }
}
In this sample code, assigning var1 will break if there are not multiple option nodes, and var2 will break if there are multiple object nodes. I could break it apart and iterate over them separately, but is there a more eloquent solution?
Would this be okay
protected function xml_resultHandler(event:ResultEvent):void
{
var data:ArrayCollection = xml.lastResult.response.option;
var valueobjects:valueObject;
for each (var characteristic:Object in data)
{
valueobject = new valueobject;
if(characteristic.option is ArrayCollection)
valueobject.var1 = characteristic.option[0].var1;
else
valueobject.var2 = characteristic.option.var2;
datamodel.addItem(valueobject);
}
}
I've used something very similar to this for result handlers where I'm not sure if the data will contain 1 or multiple rows and it seems to do the trick, seems when using the dot operator for E4X parsing it will either return an object or an arraycollection depending on the multiplicity.
精彩评论