views:

2554

answers:

3

If I have some xml like so:

<books>
    <book title="this is great" hasCover="true" />
    <book title="this is not so great" />
</books>

What's the best (or accepted) way in actionscript to check if the hasCover attribute exists before writing some code against it?

+4  A: 

See question #149206: "Best way to determine whether a XML attribute exists in Flex".

I suggested doing event.result.hasOwnProperty("@attrName") but the answer with the most upvotes (at the time of this writing) by Theo suggests this:

event.result.attribute("attrName").length() > 0
hasseg
+6  A: 

Just to add some precisions.

If you want to check if the property exists even though it's empty you should definitely use hasOwnProperty :

var propertyExists:Boolean = node.hasOwnProperty('@hasCover');

Checking the length of the content is somehow dirty and will return false if the value of the attribute is empty. You may even have a run-time error thrown as you will try to access a property(length) on a null object (hasCover) in case the attribute doesn't exist.

If you want to test if the property exists and the value is set you should try both starting with the hasOwnProperty so that the value test (eventual run-time error) gets ignored in case the attribute doesn't exist :

var propertyExistsAndContainsValue:Boolean = (node.hasOwnProperty('@hasCover') && [email protected]());
Theo.T
[email protected]() should check the length of the XMLList returned by node.@hasCover, not the length of the String value of the hasCover attribute. I say "should", because here we bump into the nasty automatic type conversion built in E4X. To check for the length of the attribute value, I would use node.@hasCover[0].length. This makes sure we get the first value in the returned XMLList, then uses the String.length property to check the length of the content.
Niko Nyman
+4  A: 

Ok - I ran across this today and a.) it was used by Ely Greenfield and b.) it's painfully simple so I have to mark it as the answer unless someone can site a reason not to...

if("@property" in node){//do something}
onekidney
Definitely the way to go. Our whole platform (Mockingbird) is built on top of XML documents and this is how I check that attributes (or child elements) exist. I believe it's byte-code-equivalent to hasOwnProperty but looks way more readable (in my opinion).
Troy Gilbert