I like to use the following syntax to check because it's easy to read, less typing and it nearly tied as the fastest method:
if ("@style" in item) // do something
To assign a value back to that attribute when you don't know the name of it before hand use the attribute
method:
var attributeName:String = "style";
var attributeWithAtSign:String = "@" + attributeName;
var item:XML = <item style="value"/>;
var itemNoAttribute:XML = <item />;
if (attributeWithAtSign in itemNoAttribute) {
trace("should not be here if attribute is not on the xml");
}
else {
trace(attributeName + " not found in " + itemNoAttribute);
}
if (attributeWithAtSign in item) {
item.attribute(attributeName)[0] = "a new value";
}
All of the following are ways to test if an attribute exists gathered from the answers listed on this question. Since there were so many I ran each in the 11.7.0.225 debug player. The value on the right is the method used. The value on the left is the lowest time in milliseconds it takes when running the code one million times. Here are the results:
807 item.hasOwnProperty("@style")
824 "@style" in item
1756 item.@style[0]
2166 (undefined != item.@["style"])
2431 (undefined != item["@style"])
3050 XML(item).attribute("style").length()>0
Performance Test code:
var item:XML = <item value="value"/>;
var attExists:Boolean;
var million:int = 1000000;
var time:int = getTimer();
for (var j:int;j<million;j++) {
attExists = XML(item).attribute("style").length()>0;
attExists = XML(item).attribute("value").length()>0;
}
var test1:int = getTimer() - time; // 3242 3050 3759 3075
time = getTimer();
for (var j:int=0;j<million;j++) {
attExists = "@style" in item;
attExists = "@value" in item;
}
var test2:int = getTimer() - time; // 1089 852 991 824
time = getTimer();
for (var j:int=0;j<million;j++) {
attExists = (undefined != item.@["style"]);
attExists = (undefined != item.@["value"]);
}
var test3:int = getTimer() - time; // 2371 2413 2790 2166
time = getTimer();
for (var j:int=0;j<million;j++) {
attExists = (undefined != item["@style"]);
attExists = (undefined != item["@value"]);
}
var test3_1:int = getTimer() - time; // 2662 3287 2941 2431
time = getTimer();
for (var j:int=0;j<million;j++) {
attExists = item.hasOwnProperty("@style");
attExists = item.hasOwnProperty("@value");
}
var test4:int = getTimer() - time; // 900 946 960 807
time = getTimer();
for (var j:int=0;j<million;j++) {
attExists = item.@style[0];
attExists = item.@value[0];
}
var test5:int = getTimer() - time; // 1838 1756 1756 1775