インデックスから要素の子にアクセスする
[] 演算子を使用すると、配列のメンバーのように要素の子にアクセスできます。子要素は、ドキュメントに現れる順序でインデックスが付けられます(最初のメンバーは 0)。
次の例では、[] 演算子を使用して XMLList の 1 つの項目を返します。
/* 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];
次の例のように、複数の括弧付きインデックスを使用して特定の項目へのパスを作成することもできます。
/* * 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];
最後に、リテラルの番号ではなく、式を括弧で囲むことができます。次の例では、Sue に関する情報の最後に <phone> 要素を追加します。
/* * 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>;
述語式を使用して特定の要素を問い合わせることもできます。述語の詳細については、述語で複数の子をフィルタ処理するを参照してください。