matb
matb

Reputation: 174

Test existence of xml attribute in as3

What is the best method to test the existence of an attribute on an XML object in ActionScript 3 ?

http://martijnvanbeek.net/weblog/40/testing_the_existance_of_an_attribute_in_xml_with_as3.html is suggesting to test using

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

and I saw comments suggesting to use:

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

But in both case, tests are case sensitive.

From the XML Specs : "XML processors should match character encoding names in a case-insensitive way" so I presume attribute name should also be match using a case-insensitive comparison.

Thank you

Upvotes: 3

Views: 3471

Answers (2)

weltraumpirat
weltraumpirat

Reputation: 22604

Please re-read your quote from the XML specs carefully:

XML processors should match character encoding names in a case-insensitive way

This is in chapter 4.3.3 of the specs describing character encoding declarations, and it refers only to the names present in the encoding value of the <?xml> processing instruction, such as "UTF-8" or "utf-8". I see absolutely no reason for this to apply to attribute names and/or element names anywhere else in the document.

In fact, there is no mention of this in section 2.3 of the specs, Common Syntactic Constructs, where names and name tokens are specified. There are a few restrictions on special characters and such, but there is absolutely no restriction on upper and lower case letters.

To make your comparison case-insensitive, you will have to do it in Flash:

for each ( var attr:XML in xml.@*) {
   if (attr.name().toString().toLowerCase() == test.toLowerCase()) // attribute present if true
}

or rather:

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

Upvotes: 9

George Profenza
George Profenza

Reputation: 51837

How about using XML's contains() method or XMLList's length() method ?

e.g.

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

trace(xml.children()[email protected]());//test if any children have the id attribute
trace(xml.child[1][email protected]());//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()

Upvotes: 0

Related Questions