在AS3中测试XML属性的存在性

3

在ActionScript 3中,测试XML对象上的属性是否存在的最佳方法是什么?

http://martijnvanbeek.net/weblog/40/testing_the_existance_of_an_attribute_in_xml_with_as3.html 建议使用以下方法进行测试:

   if ( node.@test != node.@nonexistingattribute )

我看到有评论建议使用:

 if ( node.hasOwnProperty('@test')) { // attribute qtest exists }

但是在这两种情况下,测试都是区分大小写的。
XML规范中可以看到:“XML处理器应该以不区分大小写的方式匹配字符编码名称”,因此我认为属性名称也应该使用不区分大小写的比较进行匹配。
谢谢。

哇... Flash总是用彩蛋给我惊喜... - jayarjo
虽然这可能不是一个最佳解决方案,但我会将xml作为字符串获取后转换为小写形式,再次导入为xml,并且可以安全地使用区分大小写的搜索。 - jayarjo
@jayarjo:这将使XML中的所有字符数据内容都变为小写,这不是处理XML的安全方式,除了对属性名称进行大小写不敏感搜索之外,不应用于任何其他用途。 - weltraumpirat
在我的情况下,它里面没有任何内容,只有结构,令人惊讶的是,我想不出来。但通常XML都是关于内容的,所以没错... - jayarjo
2个回答

9
请仔细阅读XML规范中的引用:

XML处理器应以不区分大小写的方式匹配字符编码名称

这在规范的第4.3.3章节中描述了字符编码声明,仅适用于<?xml>处理指令的encoding值中出现的名称,例如"UTF-8""utf-8"。我完全没有理由认为这适用于文档中任何其他位置的属性名称和/或元素名称。
事实上,在规范的第2.3节常见语法结构中没有提到这一点,其中指定了名称和名称标记。有一些特殊字符和限制,但是对于大写和小写字母没有任何限制。
要使您的比较不区分大小写,您需要在Flash中进行操作:
for each ( var attr:XML in xml.@*) {
   if (attr.name().toString().toLowerCase() == test.toLowerCase()) // attribute present if true
}

或者说:
var found:Boolean = false;
for each ( var attr:XML in xml.@*) {
    if (attr.name().toString().toLowerCase() == test.toLowerCase()) {
        found = true;
        break;
    }
}
if (found) // attribute present
else // attribute not present

你说得对,规范中并没有说明它是不区分大小写的。此外,当我使用验证器(在谷歌上可以找到很多)验证一个 xsd 时,如果元素名大小写不正确,它们会给出错误。感谢你的回答和精确度。我不再有理由编写一个 XML 不区分大小写的解析器并接受你的回答。 - matb

0

使用XML的contains()方法或者XMLList的length()方法怎么样?

例如:

var xml:XML = <root><child id="0" /><child /></root>;

trace(xml.children().@id.length());//test if any children have the id attribute
trace(xml.child[1].@id.length());//test if the second node has the id attribute
trace(xml.contains(<nephew />));//test for inexistend node using contains()
trace(xml.children().nephew.length());//test for inexistend node using legth()

"trace(xml.children().@id.length());" 和 "trace(xml.child[1].@id.length());" 是区分大小写的,而另外两种建议的方式仅适用于节点,而不是属性。 - matb
节点搜索也将区分大小写。 - weltraumpirat
此外,如果XML匹配整个节点(包括所有属性和子节点),则contains仅返回true。 - weltraumpirat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接