as3 xml check if element exists
I wa开发者_如何学Gont 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>
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 this?
for each(var item : XML in xmlData.children())
{
var hasImages : Boolean = (item.resourceImages.children().length() > 0);
if(hasImages)
trace("item has images")
}
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
}
}
精彩评论