Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

as3 xml check if element exists

I want to check if the element in this structure exists for each child. The problem is that the children don't have the same name (product,prepack) and I don't want to change the order. Additionally I can't change the XML structure.

<items>
    <product>
        <resourceImages>
            <image />
        </resourceImages>
    </product>
    <product>
        <resourceImages>
            <image />
        </resourceImages>
    </product>
    <prepack>
        <resourceImages />
    </prepack>
    <product>
        <resourceImages>
            <image />
        </resourceImages>
    </product>
    <prepack>
        <resourceImages />
    </prepack>
</items>
like image 936
chchrist Avatar asked Dec 02 '10 11:12

chchrist


3 Answers

It appears there are two ways, but the check using undefined seems preferable.

if (item.image.length() > 0)

OR

if (item.image != undefined)

But beware, this always evaluates to true regardless if the node exists.

if (item.image)

Which is weird considering the undefined check.

like image 139
loungerdork Avatar answered Nov 25 '22 09:11

loungerdork


Like this?

for each(var item : XML in xmlData.children())
{
    var hasImages : Boolean = (item.resourceImages.children().length() > 0);

    if(hasImages)
        trace("item has images")
}
like image 34
Mattias Avatar answered Nov 25 '22 09:11

Mattias


Depends also how is your first loop, but you can also check if the node is not undefined :

var xml:XML=<items>
    <product>
        <resourceImages>
            <image />
        </resourceImages>
    </product>
    <product>
        <resourceImages>
            <image />
        </resourceImages>
    </product>
    <prepack>
        <resourceImages />
    </prepack>
    <product>
        <resourceImages>
            <image />
            <image />
        </resourceImages>
    </product>
    <prepack>
        <resourceImages />
    </prepack>
</items>;

//loop on all all resourceImage node
for each (var resourceImageXML:XML in xml..resourceImages){
    // and check if node if defined
    if (resourceImageXML.image != undefined) {
        // ok node have image
    }
}
like image 24
Patrick Avatar answered Nov 25 '22 09:11

Patrick