2008-09-29 10 views
9

Tengo una respuesta XML de una llamada HTTPService con el formato de resultado e4x.La mejor manera de determinar si existe un atributo XML en Flex

 

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

que he intentado:

 

private function callback(event:ResultEvent):void { 
    if([email protected]) { 
     // error attr present 
    } 
    else { 
     // error attr not present 
    } 
} 
 

Esto no parece funcionar (siempre piensa que las salidas de los atributos de error) ¿Cuál es la mejor manera de hacer esto? Gracias.

EDIT: También he tratado de comparar el atributo en null y una cadena vacía y sin tanto éxito ...

+0

comprobar mis respuestas al final. ¡Creo que es lo que has estado buscando! :) – Rihards

Respuesta

1

he encontrado una solución, todavía me interesa si hay una manera mejor para hacer esto ...

esto funcionará:

 

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

Suponiendo que en su ejemplo event.result es un objeto XML los contenidos de los cuales son exactamente como usted envió, esto debería funcionar (debido al hecho de que la etiqueta de validación es la etiqueta raíz del XML):

var error:String = [email protected]; 
if (error != "") 
    // error 
else 
    // no error 

El ejemplo anterior asume que un Error atributo existente con un valor vacío debe ser tratado como un "no- de error" caso, sin embargo, por lo que si usted quiere saber si el atributo realidad existe o no, usted debe hacer esto:

if (event.result.hasOwnProperty("@Error")) 
    // error 
else 
    // no error 
11

usted ha encontrado la mejor manera de hacerlo:

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

El método attribute es la forma preferida de recuperar atributos si no sabe si están allí o no.

+0

Creo que es importante enfatizar que esto NO es equivalente a 'event.result.Error.length()> 0' que fallará si Error no existe. Para obtener más información, consulte: http://www.adobe.com/livedocs/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000125.html – sixtyfootersdude

+0

Creo que quiso decir "evento .result. @ Error "desde que event.result.Error buscará el nodo denominado" Error "en lugar del atributo. –

3

Esto se puede comprobar en la siguiente forma:

if (undefined == [email protected]) 

o dinámicamente

if (undefined == [email protected][attributeName]) 

Tenga en cuenta que en su ejemplo, los dos puntos recuperarán todos los descendientes en todos los niveles de manera que obtendrá una lista como resultado. Si no hay atributos de Error, obtendrá una lista vacía. Es por eso que nunca será igual a nulo.

5

Me gusta este método porque a.) Es muy simple yb.) Ely Greenfield lo usa. ;)

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

Este es un gran consejo, sin embargo, me gustaría dar un paso más y asignar algún valor al atributo si existe. ¿Cómo lo hago? Mi nombre de atributo está en una variable de cadena, y probé el nodo. @ {AttrNameString} y no funciona. ¿algunas ideas? – Vatsala

+0

'XML (node) .attribute (attrNameString) [0] =" algún valor ";' –

1

me gusta usar la siguiente sintaxis para comprobar porque es fácil de leer, escribir menos y casi atado como el método más rápido:

if ("@style" in item) // do something 

Para asignar un valor a ese atributo cuando Don sé el nombre de ella antes de mano utilice el método attribute:

var attributeName:String = "style"; 
var attributeWithAtSign:String = "@" + attributeName; 
var item:XML = <item style="value"/>; 
var itemNoAttribute:XML = <item />; 

if (attributeWithAtSign in itemNoAttribute) { 
    trace("should not be here if attribute is not on the xml"); 
} 
else { 
    trace(attributeName + " not found in " + itemNoAttribute); 
} 

if (attributeWithAtSign in item) { 
    item.attribute(attributeName)[0] = "a new value"; 
} 

Todas las maneras siguientes son para probar si un atributo existe obtenida de las respuestas que aparecen en este ques ción. Como había tantos, ejecuté cada uno en 11.7.0.225 jugador de depuración. El valor a la derecha es el método utilizado. El valor de la izquierda es el tiempo más bajo en milisegundos que se tarda al ejecutar el código un millón de veces. Aquí están los resultados:

807 item.hasOwnProperty("@style") 
824 "@style" in item 
1756 [email protected][0] 
2166 (undefined != [email protected]["style"]) 
2431 (undefined != item["@style"]) 
3050 XML(item).attribute("style").length()>0 

Rendimiento Código de ensayo:

var item:XML = <item value="value"/>; 
var attExists:Boolean; 
var million:int = 1000000; 
var time:int = getTimer(); 

for (var j:int;j<million;j++) { 
    attExists = XML(item).attribute("style").length()>0; 
    attExists = XML(item).attribute("value").length()>0; 
} 

var test1:int = getTimer() - time; // 3242 3050 3759 3075 

time = getTimer(); 

for (var j:int=0;j<million;j++) { 
    attExists = "@style" in item; 
    attExists = "@value" in item; 
} 

var test2:int = getTimer() - time; // 1089 852 991 824 

time = getTimer(); 

for (var j:int=0;j<million;j++) { 
    attExists = (undefined != [email protected]["style"]); 
    attExists = (undefined != [email protected]["value"]); 
} 

var test3:int = getTimer() - time; // 2371 2413 2790 2166 

time = getTimer(); 

for (var j:int=0;j<million;j++) { 
    attExists = (undefined != item["@style"]); 
    attExists = (undefined != item["@value"]); 
} 

var test3_1:int = getTimer() - time; // 2662 3287 2941 2431 

time = getTimer(); 

for (var j:int=0;j<million;j++) { 
    attExists = item.hasOwnProperty("@style"); 
    attExists = item.hasOwnProperty("@value"); 
} 

var test4:int = getTimer() - time; // 900 946 960 807 

time = getTimer(); 

for (var j:int=0;j<million;j++) { 
    attExists = [email protected][0]; 
    attExists = [email protected][0]; 
} 

var test5:int = getTimer() - time; // 1838 1756 1756 1775 
Cuestiones relacionadas