Accessing Attributes With the @ Operator

In the way that you access elements with the . operator, you can access attributes using the @ (attribute) operator.

/* Declare an XML variable with a literal XML value. */
var xmlEmployees = <employees>
    <employee id="111111111" dept="Sales">
        <firstname>John</firstname>
        <lastname>Walton</lastname>
        <age>25</age>
    </employee>
    <employee id="222222222" dept="Human Resources">
        <firstname>Sue</firstname>
        <lastname>Day</lastname>
        <age>32</age>
    </employee>
</employees>;
/*
 * Assign a variable with John's id number. 
 * This code returns a string containing "111111111".
 */
var xmlEmployeeID = xmlEmployees.employees.employee[0].@id;
/*
 * Set Sue's id number to "555555555".
 */
xmlEmployees.employees.employee[1].@id = "555555555";

Note: The nature of attributes and the @ operator makes it necessary to use the thisXML property when filtering using the @ operator:

/* 
 * Find the <employee> element where the id attribute is 222222222.
 * Return the corresponding last name.
 * This code returns <lastname>Day</lastname>.
 */
var ageXML = xmlEmployees..employee.(thisXML.@id == "222222222").lastname;

You can also retrieve all of an element's attributes with the @* operator. For example, the following line would return all of the attributes for the first employee element.

var attrs = xmlEmployees.employees.employee[0].@*;

You could loop through the returned attributes with code such as the following, printing the value for each:

for (i = 0; i < attrs.length; i++)
{
    currentAttr = attrs[i];
    if (currentAttr.getName() == "id")
    {
        print("id attribute's value is " + currentAttr);
    }
    else if (currentAttr.getName() == "dept")
    {
        print("dept attribute's value is " + currentAttr);
    }
}

Note: You can also access namespaced attributes, as described in Filtering By Namespace.

Related Topics

attribute Function

attributes Function