as3 xml check if element exists
14,080
Solution 1
Like this?
for each(var item : XML in xmlData.children())
{
var hasImages : Boolean = (item.resourceImages.children().length() > 0);
if(hasImages)
trace("item has images")
}
Solution 2
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.
Solution 3
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
}
}
Author by
chchrist
Updated on July 28, 2022Comments
-
chchrist almost 2 years
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>
-
chchrist over 13 yearsI've changed the example. I need to run these checks in a for loop. Can you give an example?
-
Mattias over 13 yearsWhat element do you want to check? Image?
-
chchrist over 13 yearsyes I need to check in a for loop if the image element exists. But I don't know how to find the length()