1

I am trying to access an XMLList item and convert it to am XML object.

I am using this expression:

masonicXML.item.(@style_number == styleNum)

For example if there is a match everything works fine but if there is not a match then I get an error when I try cast it as XML saying that it has to be well formed. So I need to make sure that the expression gets a match before I cast it as XML. I tried setting it to an XMLList variable and checking if it as a text() propertie like this:

var defaultItem:XMLList = DataModel.instance.masonicXML.item.(@style_number == styleNum);
                    if(defaultItem.text())
                    {
                        DataModel.instance.selectedItem = XML(defaultItem);
                    }

But it still give me an error if theres no match. It works fine if there is a match.

THANKS!

JD Isaacks
  • 56,088
  • 93
  • 276
  • 422

3 Answers3

1

In my experience, the simplest way to check for results is to grab the 0th element of the list and see if it's null.

Here is your code sample with a few tweaks. Notice that I've changed the type of defaultItem from XMLList to XML, and I'm assigning it to the 0th element of the list.

var defaultItem:XML = 
    DataModel.instance.masonicXML.item.(@style_number == styleNum)[0];
if( defaultItem != null ) 
{
    DataModel.instance.selectedItem = defaultItem;
}
Matt Dillard
  • 14,677
  • 7
  • 51
  • 61
0

OK I got it to work with this:

if(String(defaultItem.@style_number).length)
JD Isaacks
  • 56,088
  • 93
  • 276
  • 422
0

Matt's null check is a good solution. (Unless there is the possibility of having null items within an XMLList.. probably not, but I haven't verified this.)

You can also check for the length of the XMLList without casting it to a String:

if (defaultItem.@style_number.length() > 0)

The difference to String and Array is that with an XMLList, length() is a method instead of a property.

Niko Nyman
  • 1,916
  • 2
  • 16
  • 26