Reputation: 3254
I have the following XML:
<document>
<homeitems>
<homeitem>
<itemURL>URL1.html</itemURL>
</homeitem>
<homeitem>
<itemURL>URL2.html</itemURL>
</homeitem>
<homeitem>
<itemURL>URL3.html</itemURL>
<itemImage>image3.jpg</itemImage>
</homeitem>
</homeitems>
</document>
And the following code that parses it:
var XMLData:XML = new XML(LoaderMax.getContent("xmlDoc")); // loads XML
var numitems = XMLData.homeitems.homeitem.length();
for (var i=0;i<numitems;i++) {
if ((XMLData.homeitems.homeitem[i].itemImage) && (XMLData.homeitems.homeitem[i].itemImage!=="")) {
trace("Loading image "+XMLData.homeitems.homeitem[i].itemImage);
}
}
Trace result:
Loading image
Loading image
Loading image image3.jpg
WHY?!?!? Shouldn't it skip the items that don't have images? Am I stupid?
Upvotes: 0
Views: 2230
Reputation: 15717
You can see that your test if (XMLData.homeitems.homeitem[i].itemImage)
evaluate to true (just do a trace(Boolean(XMLData.homeitems.homeitem[i].itemImage)
you will see true).
Also don't compare a node to a String
use the toString
method of the node or cast it explicitely to a String
(i.e. String(XMLData.homeitems.homeitem[i].itemImage)!=""
or XMLData.homeitems.homeitem[i].itemImage.toString()!=""
)
There is multiple way todo it :
You can test if the node is undefined :
if (XMLData.homeitems.homeitem[i].itemImage != undefined)
Use hasOwnProperty method :
if (XMLData.homeitems.homeitem[i].hasOwnProperty('itemImage'))
And you can also cast your itemImage
to a String and see if it's != ""
:
if (String(XMLData.homeitems.homeitem[i].itemImage) != "")
Using e4x and foreach you can have a cleaner code for your loop :
for each(var homeItem:XML in XMLData.homeitems.homeitem) {
var itemImage:String = String(homeItem.itemImage)
if (itemImage!="") {
trace("Loading image "+itemImage);
}
}
Upvotes: 1
Reputation: 1996
It's enough if you compare with !=
not !==
if ((XMLData.homeitems.homeitem[i].itemImage) && (XMLData.homeitems.homeitem[i].itemImage!="")) {
/* do somethong here */
}
Upvotes: 0