Check if item exists in XML with AS3

221 Views Asked by At

So I am pulling in this XML data using AS3 and storing it as myXML:

<Questions>
    <id>1</id>
    <question>
    This is question 1.
    </question>
</Questions>
<Questions>
    <id>3</id>
    <question>
    This is question 3.
    </question>
</Questions>

Now I want to check if an id is found within that XML. I am currently using this, but it always traces "NOT FOUND" -

for (var i: Number = 1; i < 3; i++) {
    if (myXML.Questions.(@id == i).length() > 0) {
        trace("FOUND")
    } else {
        trace("NOT FOUND");
    }
}
3

There are 3 best solutions below

0
On BEST ANSWER

There are no loop necessary. Vesper solution would work but in theory is very expensive and slow. PO was also pretty close but he's using @id as if the id element was an attribute. The solution is simply:

var result:XMLList = xml.Questions.(id == 1);

You either got a valid XMLList or you don't but that's all it takes.

Also do not use that code logic:

if(xml.Questions.(id == 1).length() > 0)

It creates an unnecessary additional xml search since if true you would then have to call "xml.Questions.(id == 1)" again to get the list. Instead call it and store the result first, then check the length if you wish so.

0
On

I haven been using AS3/XML for a while, but I think if you want to find any id (regardless of the number), you could try:

myXML.Questions.id.length() > 0

As to why it always traces NOT FOUND in your code, it's because the @ sign it's for attributes, not for elements. So it's trying to find:

<Questions id=1>
    ...
</Questions>
0
On

With this XML your Questions should be an array internally, that is, trace(myXML.Questions.length()) should return more than 1, so you are to iterate through myXML.Questions and check the node's id to be equal to your i.

for (var i: Number = 1; i < 3; i++) {
    var b:Boolean=false;
    for (var j:int=0;j<myXML.Questions.length();j++) {
        if (myXML.Questions[j].id==i) b=true;
    }
    if (b){
        trace(i,"FOUND")
    } else {
        trace(i,"NOT FOUND");
    }
}