How to Properly Loop Through Result Objects in Flex

When working with Apache Flex, developers quite commonly encounter the need to loop through data retrieved from a web service. A common scenario is handling XML data returned via an HTTPService call. However, many face issues, especially when the response includes a varying number of rows. In this blog post, we will explore how to correctly loop through these XML result objects without running into errors.

The Problem: Looping Through XML Data

In a typical situation, you might make an HTTPService call and receive XML data structured like this:

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

When processing this data, many developers use a for-loop to iterate through the “Row” nodes using the following code:

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!');
}

Although this code works correctly when multiple “Row” nodes are present, it breaks when there is only one “Row” node because length is not a property of the XMLList object returned. In such cases, it may lead to unexpected errors.

The Solution: Using for each Loop

Understanding XMLList Length

The key to solving the problem is recognizing that length is a method of XMLList, not a property. Therefore, the correct way to get the number of rows should be:

event.result.DataTable.Row.length();

However, querying the length directly may still lead to confusion, especially for developers who might overlook it or have inconsistent XML responses.

Best Practice: Use for each Loop

To enhance code clarity and avoid potential errors, it’s best to use a for each loop when working with XMLList. This method is safer and more idiomatic for iterating over the XML nodes:

for each (var node:XML in event.result.DataTable.Row) {
    if (node.text == "foo") {
        mx.controls.Alert.show('foo found!');
    }
}

Benefits of for each Loop:

  • Readability: The code is simpler and easier to read.
  • Robustness: It circumvents issues associated with accessing lengths, making it less error-prone.
  • Flexibility: Works seamlessly with varying numbers of child nodes.

Conclusion

Handling XML data in Flash and Apache Flex can be tricky if not done correctly. By using a for each loop to iterate through XMLList results from HTTPService calls, you not only prevent errors associated with single child nodes but also create cleaner and more maintainable code.

Implementing this practice will enhance your code quality and reduce the likelihood of runtime issues when working with XML data in your Flex applications.