20.9.读取元素的属性

问题
我想解析出元素的属性值
解决办法
使用attributes( ) 方法返回指定元素的属性列表,或者通过名称用E4X的@操作符或attribute( )方法访问属性
讨论
通过attributes( ) 方法返回当前元素节点所有属性的XMLList 对象,XMLList对象是可索引的,很像Array对象,可通过索引值访问属性值:
+展开
-ActionScript
var fruit:XML = <fruit name="Apple" color="red" />;
var attributes:XMLList = fruit.attributes( );
// 显示: Apple
trace( attributes[0] );
// 显示: red
trace( attributes[1] );

上面的例子中只显示出属性值,用name( ) 方法可显示出属性名,看下面的代码:
+展开
-ActionScript
var fruit:XML = <fruit name="Apple" color="red" />;
// 显示: color
trace( fruit.attributes( )[1].name( ) );
通过for each 循环语句可遍历所有属性名和属性值,如:
var fruit:XML = <fruit name="Apple" color="red" />;
for each ( var attribute:XML in fruit.attributes( ) ) {
/* 显示:
name = Apple
color = red
*/

trace( attribute.name( ) + " = " + attribute.toString( ) );
}

下面是E4X的写法:
+展开
-ActionScript
var fruit:XML = <fruit name="Apple" color="red" />;
// 显示: red
trace( fruit.@color );

还有种方法,可使用attribute( ) 方法并传入属性名作为参数,得到属性值:
+展开
-ActionScript
var fruit:XML = <fruit name="Apple" color="red" />;
// 显示: red
trace( fruit.attribute("color") );

用(*)和@操作符可访问所有属性值,有些类似于attributes( )方法:
+展开
-ActionScript
var fruit:XML = <fruit name="Apple" color="red" />;
// 显示: Apple
trace( fruit.@*[0] );
// 显示: red
trace( fruit.@*[1] );
// 显示: 2
trace( fruit.@*.length( ) );

E4X 语法是很强大的,如果XML饱含有多个元素且有相同名称的属性,比如下面例子中的price属性,看用E4X如何统计出price:
+展开
-ActionScript
// Create a fictitious shopping cart
var cart:XML = <cart>
<item price=".98">crayons</item>
<item price="3.29">pencils</item>
<group>
<item price=".48">blue pen</item>
<item price=".48">black pen</item>
</group>
</cart>;
// Create a total variable to represent represent the cart total
var total:Number = 0;
// Find every price attribute, and add its value to the running total
for each ( var price:XML in cart..@price ) {
total += Number(price);
}
// 显示: 5.23
trace( total );

如果属性名含有特殊字符,可用[]进行访问:
+展开
-ActionScript
var example:XML = <example bad-variable-name="yes" color12="blue" />;
var num:Number = 12;
// 显示: yes
trace( example.@["bad-variable-name"] );
// 显示: blue
trace( example.@["color" + num] ); 

加支付宝好友偷能量挖...


评论(0)网络
阅读(112)喜欢(0)flash/flex/fcs/AIR