views:

4232

answers:

3

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 webservie result event is fired I do something like this:


for(var i:int=0;i<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 then 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

+1  A: 

Row isn't an array unless there are multiple Row elements. It is annoying. You have to do something like this, but I haven't written AS3 in a while so I forget if there's an exists function.

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

I would store it in an Xml object and then use its methods to search for the node value you need.

var returnedXml:Xml = new Xml(event.result.toString());
Shawn Simon
+2  A: 

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 )
Theo