埋め込み式で XML を動的に解決する

XML を処理するときには、要素および属性の値を解決または変更する簡略的な手段として埋め込み式を使用できます。{}(中括弧)演算子を使用して、変数への割り当て用に文字列全体が XML に変換される前に評価すべき式を囲むことができます。次の例の ECMAScript は、id 値が <employee> の子要素に格納されず、その要素の id 属性に格納されるように xmlEmployees 変数の XML を再構成します。

/* Declare an XML variable with a literal XML value. */
var xmlEmployees = <employees>
    <employee>
        <id>111111111</id>
        <firstname>John</firstname>
        <lastname>Walton</lastname>
        <age>25</age>
    </employee>
    <employee>
        <id>222222222</id> 
        <firstname>Sue</firstname>
        <lastname>Day</lastname>
        <age>32</age>
    </employee>
</employees>;
/*
 * Loop through the list of employees, restructuring the <employee> element
 * to make the id element an attribute of the <employee> element.
 */
for(e in xmlEmployees..employee){
    var newStructure = 
        <employee ssn={e.id}>
            <first_name>{e.firstname}</first_name>
            <last_name>{e.lastname}</last_name>
            <age>{e.age}</age>
        </employee>;
}

{} を使用して要素の名前を動的に解決することもできますが、{} の間の値が空の文字列であってはなりません。たとえば、<{}>someValue</{}> は無効です。

関連トピック

ECMAScript 言語の拡張機能の概要