E4X: Use string as attribute name in expression?
-
03-07-2019 - |
Question
I have a function that has this line:
var returnString:String = items[0].@month;
@month is an attibute on an XML node like so:
<xmlnode month="JAN"/>
OK but I need to abstract the attribute name so I can pass a string to the function and get the contents of the attribute with the name matching the string I passed. So for example If I call the function like this function("stone") it returns items[0].@stone. I hope this is clear.
Does anyone know how to do what I am after?
Thanks.
Solution
You'll want to use attribute('stone') rather than @stone, its the same thing, @stone is just a shorthand way of writing it.
OTHER TIPS
You can write this as:
var attrName:String = "month";
return items[0].@[ attrName ];
not only that, but if you ever want to assign a value to an attribute using a variable for the attribute name, you can do this (although it is not documented) like so:
public function setAttr(obj:XML, attrName:String, value:String):void{ obj.@[attrName] = value; }