2
votes

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.

3
Looking a all the comments I cant help but think there is something wrong here. I tested the solutions that were described by your answers and am not getting the results that you guys are talking about. ~~~~~ So I have some basic xml with an attribute ' id="hey" ' ~~~~~ trace(xml.@id); // traces: hey ~~~~~ trace(xml.@['id']); // traces blank ~~~~~ trace(xml.attribute('id')); // traces blank ~~~~~ also making 'id' into a String (from a literal) doesn't help any. - gltovar

3 Answers

6
votes

You'll want to use attribute('stone') rather than @stone, its the same thing, @stone is just a shorthand way of writing it.

2
votes

You can write this as:

var attrName:String = "month";
return items[0].@[ attrName ];
2
votes

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;
  }