9

I am reading in an XML file in AS3. I need to find out if an attribute exists on a node. I want to do something like:

if(xmlIn.attribute("id")){
foo(xmlIn.attribute("id"); // xmlIn is of type XML
}

This doesn't work however. The above if statement is always true, even if the attribute id isn't on the node.

0

5 Answers 5

18

You have to do this instead:

if(xmlIn.hasOwnProperty("@id")){
    foo(xmlIn.attribute("id"); // xmlIn is of type XML
}

In the XML E4X parsing, you have to use hasOwnProperty to check if a property for the attribute as been set on the E4X XML object node. Hope this helps!

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I thought my solution was hacky. The hasOwnProperty method did the trick.
How do you check if it is empty?
7

I found 4 ways:

if ('@id' in xmlIn)
if (xmlIn.hasOwnProperty("@id"))
if ([email protected]() > 0)
if (xmlIn.attribute("id").length() > 0)

and I prefere first method:

if ('@id' in xmlIn) 
{
    foo(xmlIn.@id);
}

Comments

4

easiest way:

(@id in xmlIn)

this will return true if id attrtibute exists and false otherwise.

1 Comment

Operator 'in' need string, you must write ('@id' in xmlIn)
1

I generally use:

if (xmlIn.@id != undefined)

It also works for object properties:

if (obj.id != undefined)

Comments

0

I figured this out. For anyone else having the same issue it seems like checking that the length of the attribute is greater than 0 works.

if(xmlIn.attribute("id").length() >0){
foo(xmlIn.attribute("id"); // xmlIn is of type XML
}

I don't know if this will work in all cases, but it is working for me. If there is a better way to do this please post it.

2 Comments

Hey Boundless, see my other answer. Using hasOwnProperty is much more efficient than creating an attribute array and then count the array index to just determine if it exists. However, if performance isn't an issue, this will definitely work too.
@JonathanDunlap Thanks, performance is an issue (but I still use Flash, what a shame). Your above solution with hasOwnProperty works great, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.