In actionscript, what's the best way to check if an xml node property exists?

If I have xml:

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

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

+4
source share
3 answers

Just add some fixes.

If you want to check if a property exists, even if it is 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 attribute value is empty. You might even get a runtime error, because you are trying to access a property (length) for a null object (hasCover) in case the attribute does not exist.

If you want to check if a property exists and the value is set, you should try both , starting with hasOwnProperty , so that the value test (possible runtime error) is ignored if the attribute does not exist:

 var propertyExistsAndContainsValue:Boolean = (node.hasOwnProperty('@hasCover') && node.@hasCover.length ()); 
+13
source

Good - I came across this today and a). It was used by Eli Greenfield and B.), it was painfully simple, so I should mark this as an answer, if someone can not justify the reason for not ...

 if("@property" in node){//do something} 
+6
source

See question # 149206: "The best way to determine if an XML attribute exists in Flex . "

I suggested making event.result.hasOwnProperty("@attrName") , but the answer with the most revolutions (as of this writing) Theo suggests the following:

 event.result.attribute("attrName").length() > 0 
+5
source

All Articles