Accessing Element Children Through Their Index

You can use the [] operator to access the children of an element as if they were members of an array. The children are indexed in the order in which they appear in the document, with the first member starting at 0.

The following example illustrates using the [] operator to return a single item in an XMLList.

/* 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 first name of the first employee in the list. 
 * This code returns an XMLList type containing "John".
 */
var name = xmlEmployees.employees.employee[0].firstname;
/*

 * Return the first <employee> element.
 * This code returns an XML type with all of the first <employee> element:
 *    <employee id="111111111">
 *        <firstname>John</firstname>
 *        <lastname>Walton</lastname>
 *        <age>25</age>
 *    </employee>
 */
var firstEmployee = xmlEmployees.employees.employee[0];

You can also use multiple bracketed indices to build a path to a specific item, as in the following example:

/*
 * Return the last name of the first employee in the list. 
 * This code returns an XML type containing <lastname>Walton</lastname>.
 */
var name = xmlEmployees.employees.employee[0][1];

Finally, you can enclose an expression in the brackets, rather than a literal number. The following example adds a <phone> element to the end of the information about Sue.

/*
 * Return the last name of the second employee in the list. 
 * This code returns an XML type containing <lastname>Day</lastname>.
 */
var e = xmlEmployees.employees.employee[1];
/* 
 * Use the expression to calculate the number of children in the second <employee> element
 * then add a new XML value at the end.
 */
e[e.children().length] = <phone>foo</phone>;

You can also query for specific element through predicate expressions. For more information on predicates, see Filtering Multiple Children with Predicates.

Related Topics

Accessing Element Children Iteratively

Filtering Multiple Children with Predicates

Creating and Using XML Variables