# Accessing Element Children Iteratively

You can write code that iteratively accesses an XML element list in a manner similar to accessing an array. Using the XMLList type, the extended ECMAScript interpreter automatically handles repeating elements as if they were members of an array.

    /* Declare an XML variable with a literal XML value. */
    var xmlEmployees = <employees>
        <employee id="111111111">
            <firstname>John</firstname>
            <lastname>Walton</lastname>
            <age>25</age>
        </employee>
        <employee id="222222222">
            <firstname>Sue</firstname>
            <lastname>Day</lastname>
            <age>32</age>
        </employee>
    </employees>;
    /*
     * Return the average age of the employees.
     * This code produces an ECMAScript number containing "28.5".
     */
        var intAgeTotal = 0;
        var ageValues = xmlEmployees..age;
        /* Loop through the <age> element values, adding them together. */
        for (a in xmlEmployees..age) {
            intAgeTotal += new Number(a);
        }
        /* Compute the average age. */
        var intAgeAvg = intAgeTotal / ageValues.length;

Note: The for...in statement works differently for XML than it does for native ECMAScript arrays. With native ECMAScript arrays, for...in assigns the loop variable over the domain of the array. In other words, the variable represented by a above would be the index of the current item. With XML, for...in assigns the loop variable over the range of the array. In other words, because the example above is operating on an XMLList, a holds the current item's value.

Related Topics

Accessing Element Children Through Their Index