Actionscript – How to loop through result objects in Flex

actionscriptactionscript-3apache-flex

I am having problems manually looping through xml data that is received via an HTTPService call, the xml looks something like this:

<DataTable>
    <Row>
        <text>foo</text>
    </Row>
    <Row>
        <text>bar</text>
    </Row>
</DataTable>

When the webservice result event is fired I do something like this:

for(var i:int=0;i&lt;event.result.DataTable.Row.length;i++)
{
    if(event.result.DataTable.Row[i].text == "foo")
        mx.controls.Alert.show('foo found!');
}

This code works then there is more than 1 "Row" nodes returned. However, it seems that if there is only one "Row" node then the event.DataTable.Row object is not an error and the code subsequently breaks.

What is the proper way to loop through the HTTPService result object? Do I need to convert it to some type of XMLList collection or an ArrayCollection? I have tried setting the resultFormat to e4x and that has yet to fix the problem…

Thanks.

Best Answer

The problem lies in this statement

event.result.DataTable.Row.length

length is not a property of XMLList, but a method:

event.result.DataTable.Row.length()

it's confusing, but that's the way it is.

Addition: actually, the safest thing to do is to always use a for each loop when iterating over XMLLists, that way you never make the mistake, it's less code, and easier to read:

for each ( var node : XML in event.result.DataTable.Row )