. 演算子で要素の子にアクセスする
.(ドット)演算子を使用すると、コレクション オブジェクトのメンバーを指定するように要素のパスを作成できます。. 演算子は、左側のオペランドの子を調べ、右側のオペランドと名前が一致する子を返します。子は、ドキュメントでの順序で返されます。
次の例では、. 演算子を使用して単一の値または要素を返します。
/* 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];
次の例のように、. 演算子を使用すると、繰り返し要素で複数の項目がある XMLList を返すように指定できます。
/* * Return all of the <employee> elements. * This code returns an XMLList containing the following: * <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> */ var employees = xmlEmployees.employees.employee;
次の例のように、. 演算子を使用して新しい値を割り当てることもできます。
/* * Change John's name to Biff. */ xmlEmployees.employees.employee[0].firstname = "Biff"; /* * Set the entire first <employee> element to a new value. */ xmlEmployees.employees.employee[0] = <employee id="111111111"> <first>Armin</first>
<last>HooHaw</last>
<age>91</age>
</employee>;
要素の名前が ECMAScript キーワードまたは関数名と衝突する場合は、代わりに次の構文を使用できます。ECMAScript キーワード用と関数名用の 2 通りの解決策があります。
/* * Return all of the <if> elements. * This avoids a conflict with the "if" ECMAScript keyword. */ var ifs = xmlData.product_description["if"]; /* * Return the first <parent> element. * This avoids a conflict with the parent function. */ var firstParent = xmlFamilies.kid.::parent[0];