views:

6664

answers:

7

I have a XML response from an HTTPService call with the e4x result format.


<?xml version="1.0" encoding="utf-8"?>
<Validation Error="Invalid Username/Password Combination" />

I have tried:


private function callback(event:ResultEvent):void {
    if(event.result..@Error) {
        // error attr present
    }
    else {
        // error attr not present
    }
}

This does not seem to work (it always thinks that the error attribute exits) what is the best way to do this? thanks.

EDIT: I have also tried to compare the attribute to null and an empty string without such success...

+1  A: 

I have figured out a solution, I'm still interested if there is a better way to do this...

This will work:


private function callback(event:ResultEvent):void {
    if(event.result.attribute("Error").length()) {
        // error attr present
    }
    else {
        // error attr not present
    }
}

mmattax
+2  A: 

Assuming that in your example event.result is an XML object the contents of which are exactly as you posted, this should work (due to the fact that the Validation tag is the root tag of the XML):

var error:String = event.result.@Error;
if (error != "")
    // error
else
    // no error

The above example will assume that an existing Error attribute with an empty value should be treated as a "no-error" case, though, so if you want to know if the attribute actually exists or not, you should do this:

if (event.result.hasOwnProperty("@Error"))
    // error
else
    // no error
hasseg
+5  A: 

You have found the best way to do it:

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

The attribute method is the preferred way to retrieve attributes if you don't know if they are there or not.

Theo
+2  A: 

You can check this in the following way:

if (undefined == event.result.@Error)

or dynamically

if (undefined == event.result.@[attributeName])

Note that in your example, the two dots will retrieve all descendants on all levels so you'll get a list as a result. If there are no Error attributes, you'll get an empty list. That's why it will never equal null.

Christophe Herreman
+2  A: 

I like this method because a.) it's painfully simple and b.) Ely Greenfield uses it. ;)

if("@property" in node){//do something}
onekidney
This is a great tip, however I would like to go one step further and assign some value to the attribute if it exists. How do I do it?My attribute name is in a string variable, and I tried node.@{attrNameString} and it dint work. any ideas?
Vatsala
A: 

I likey! Works for me. Thanks a million onekidney.

CJ
A: 

Here you go:

if(event.result.@error[0]){
    //exists 
}

Easy, eh? :)

Richards