0

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?

2 Answers 2

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

It's enough if you compare with != not !==

if ((XMLData.homeitems.homeitem[i].itemImage) && (XMLData.homeitems.homeitem[i].itemImage!="")) { 
    /* do somethong here */ 
}

3 Comments

Ok, but that doesn't change anything. Output is still the same
Try XMLData.homeitems.homeitem[i].itemImage != NULL && XMLData.homeitems.homeitem[i].itemImage != ""
1120: Access of undefined property NULL, should have been lowercase null... but still no change - the conditional still evaluates as true

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.