在actionscript中,检查xml节点属性是否存在的最佳方法是什么?

one*_*ney 4 xml apache-flex flash properties actionscript-3

如果我有一些像这样的xml:

<books>
    <book title="this is great" hasCover="true" />
    <book title="this is not so great" />
</books>
Run Code Online (Sandbox Code Playgroud)

在针对它编写一些代码之前检查hasCover属性是否存在的actionscript中最好(或接受)的方法是什么?

The*_*o.T 13

只是为了增加一些精确度.

如果你想检查属性是否存在,即使它是空的,你肯定应该使用hasOwnProperty:

var propertyExists:Boolean = node.hasOwnProperty('@hasCover');
Run Code Online (Sandbox Code Playgroud)

检查内容的长度有点脏,如果属性的值为空,则返回false.您甚至可能会抛出运行时错误,因为如果该属性不存在,您将尝试访问空对象(hasCover)上的属性(长度).

如果要测试属性是否存在且值已设置,则应尝试以hasOwnProperty开头,以便在属性不存在时忽略值test(最终运行时错误):

var propertyExistsAndContainsValue:Boolean = (node.hasOwnProperty('@hasCover') && node.@hasCover.length());
Run Code Online (Sandbox Code Playgroud)


one*_*ney 6

好的 - 今天我遇到了这个问题.)它被Ely Greenfield和b使用了.)它很简单,所以我必须将它标记为答案,除非有人能找到一个理由不......

if("@property" in node){//do something}
Run Code Online (Sandbox Code Playgroud)


has*_*seg 5

请参阅问题#149206:"确定Flex中是否存在XML属性的最佳方法".

我建议这样做,event.result.hasOwnProperty("@attrName")但Theo 的最热门投票(在撰写本文时)的答案表明:

event.result.attribute("attrName").length() > 0
Run Code Online (Sandbox Code Playgroud)