chchrist
chchrist

Reputation: 19802

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>

Upvotes: 8

Views: 14159

Answers (3)

loungerdork
loungerdork

Reputation: 991

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.

Upvotes: 10

Patrick
Patrick

Reputation: 15717

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
    }
}

Upvotes: 6

Mattias
Mattias

Reputation: 3907

Like this?

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

    if(hasImages)
        trace("item has images")
}

Upvotes: 7

Related Questions