【问题标题】:In actionscript, what's the best way to check if a xml node property exists?在 actionscript 中,检查 xml 节点属性是否存在的最佳方法是什么?
【发布时间】:2009-02-25 01:01:34
【问题描述】:

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

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

在针对 hasCover 属性编写代码之前检查 hasCover 属性是否存在的最佳(或可接受的)方法是什么?

【问题讨论】:

    标签: xml apache-flex flash actionscript-3 properties


    【解决方案1】:

    只是为了增加一些精度。

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

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

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

    如果您想测试属性是否存在并设置了值,您应该尝试 从 hasOwnProperty 开始,以便在属性的情况下忽略值测试(最终的运行时错误)不存在:

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

    【讨论】:

    • node.@hasCover.length() 应该检查 node.@hasCover 返回的 XMLList 的长度,而不是 hasCover 属性的字符串值的长度。我说“应该”,因为在这里我们遇到了 E4X 中内置的讨厌的自动类型转换。要检查属性值的长度,我会使用 node.@hasCover[0].length。这确保我们获得返回的 XMLList 中的第一个值,然后使用 String.length 属性检查内容的长度。
    【解决方案2】:

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

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

    【讨论】:

    • 绝对是要走的路。我们的整个平台(Mockingbird)建立在 XML 文档之上,这就是我检查属性(或子元素)是否存在的方式。我相信它的字节码等效于 hasOwnProperty 但看起来更具可读性(在我看来)。
    【解决方案3】:

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

    我建议这样做 event.result.hasOwnProperty("@attrName") 但 Theo 的 the answer with the most upvotes(在撰写本文时)建议这样做:

    event.result.attribute("attrName").length() > 0
    

    【讨论】:

      猜你喜欢
      • 2012-04-02
      • 2013-10-13
      • 2023-04-03
      • 2018-08-19
      • 2011-05-25
      • 2012-08-29
      • 2011-03-20
      • 2011-12-25
      • 2010-09-18
      相关资源
      最近更新 更多