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

↘锁芯ラ 提交于 2019-12-12 12:18:34

问题


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?


回答1:


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') && node.@hasCover.length());



回答2:


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}



回答3:


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


来源:https://stackoverflow.com/questions/584361/in-actionscript-whats-the-best-way-to-check-if-a-xml-node-property-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!