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">
        <firstname>John</firstname>
        <lastname>Walton</lastname>
        <age>25</age>
    </employee>
    <employee id="222222222">
        <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;

Related Topics

attribute Function

attributes Function