2

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.

JD Isaacks
  • 56,088
  • 93
  • 276
  • 422
  • 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 Feb 14 '11 at 05:14

3 Answers3

6

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

quoo
  • 6,237
  • 1
  • 19
  • 36
  • It worked for the person who originally asked the question as well in several of my applications i was working on at the time the question was posed. Perhaps your problem is slightly different. – quoo Jun 29 '11 at 20:12
  • The reason you're running into problems is that you're using a custom namespace. Our answers do not take into account the use of a custom namespace as it was not part of the original question. If you remove the custom namespace from your code, our answers should all work (although I have not tested the others). If you truly wanted help with your problem though, you should of posed your own question instead of maliciously down voting perfectly valid answers. I suggest you read this article to better understand of why your use of a namespace caused your problem: http://adobe.ly/lcSLZS – quoo Jun 30 '11 at 13:53
2

You can write this as:

var attrName:String = "month";
return items[0].@[ attrName ];
darronschall
  • 859
  • 5
  • 7
2

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;
  }
Jorel
  • 153
  • 2
  • 14