属性値を取得するためのメソッドとしては attributes() と attribute() があります。
public attributes() : XMLList public attribute(attributeName:String) : *
attributes() は対象となるノードに含まれる全ての属性値を返します。子孫のノードの属性は含みません(念のため)。戻り値の型は XMLList です。複数のオブジェクトを持つ XMLList に対して呼ばれた場合はリスト内の個々のオブジェクトの属性値をまとめて返します。
attribute() は取得する属性の名前を引数で指定します。その他の動作は基本的に attributes() と同様です。こちらのメソッドも戻り値の型は XMLList (のはず)です。
使い方の例を示します。
var myOrder:XML = <order> <item id="1" quantity="1"> <name>fresh burger</name> <price>300</price> </item> <item id="2" quantity="1"> <name>french fries</name> <price>170</price> </item> </order>; trace(myOrder.item.attributes()); // 1121 trace(myOrder.item.attribute("id")); // 12
toString() メソッドは(toXMLString() メソッドも)属性値しか返しません。なので上記の出力だけを見ると attributes() メソッドの方はどんな属性の値なのかという情報が分かりませんね。そんなときは name() メソッドが役に立ちます。XMLList 内のオブジェクト一つ一つに呼び出すことで名前を知ることができます。
trace(myOrder.item.attributes()[0].name()); // id trace(myOrder.item.attributes()[0]); // 1 trace(myOrder.item.attributes()[1].name()); // quantity trace(myOrder.item.attributes()[1]); // 1
@ と attribute()
@と変数を組み合わせても attribute() メソッドと同じように属性値を得ることができます。以下の3つの記述はそれぞれ同じ値になります。一番下のは前の記事で要素を取り出す方法として紹介したものと同じ形式です。
trace(myOrder.item.attribute("quantity")); trace(myOrder.item.@["quantity"]); trace(myOrder.item["@quantity"]); // どの場合も 11 が出力される
コメントする