views:

70

answers:

1
There is an XMLList of items, each item has three properties: prop1,
prop2, and prop3.
There are two TextAreas, t1 and t2.
t1 displays the XMLList.toString
t2 is blank
There are two buttons: Show and Clear.
When you click Show, the following should happen:
For each item in the XMLList, if prop3 is false and prop1 is "BB",
then add that item's prop2 to the text of t2.
My code is below.
It's only showing some of the results, not all expected. (It should show L3a and L3y. It only shows L3y.)
What am I doing wrong?
===
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
 [Bindable]
 private var xmlList:XMLList =
  <>
  <item prop1="AA" prop2="L0" prop3="true" >
   <item prop1="AA" prop2="L1a" prop3="true" > 
         <item prop1="AA" prop2="L2a" prop3="true" >
          <item prop1="BB" prop2="L3a" prop3="false" />
          <item prop1="AA" prop2="L3b" prop3="false" />
         </item>
      </item>
      <item prop1="AA" prop2="L1b" prop3="true" > 
    <item  prop1="AA" prop2="L2x" prop3="true" >
     <item prop1="AA" prop2="L3x" prop3="false" />
    </item>
    <item  prop1="AA" prop2="L2y" prop3="true" >
     <item prop1="BB" prop2="L3y" prop3="false" />
    </item>
   </item>
  </item>  
  </>;
 private function showBBs():void{
  lookForBBs(xmlList.children());
 }
 private function lookForBBs(list:XMLList):void{
  for each (var x:XML in list){
   if (x.item.@prop3 == "false"){
    if (x.item.@prop1 == "BB"){
     t2.text += x.item.@prop2+"\n";
    } 
   }
   else{
    lookForBBs(x.children());
   }
  }
 }
]]>
</mx:Script>
 <mx:HBox width="100%" height="100%">
  <mx:TextArea id="t1" text="{xmlList.toString()}" width="100%" height="100%"/>
  <mx:Button label="Show" click="showBBs()"/>
  <mx:Button label="Clear" click="{t2.text=''}"/>
  <mx:TextArea id="t2" text="" width="100%" height="100%"/>
 </mx:HBox>
</mx:Application>
A: 

The problem is using "x.item.@propX" instead of simply "x.@propX" in lookForBBs(). Using "x.item" examines all the children of x with the item tag, and concatenates the results. So including this trace inside your for each loop:

trace(x.item.@prop1+", "+x.item.@prop2+", "+x.item.@prop3);

produces the following:

AA, L2a, true
BBAA, L3aL3b, falsefalse
, , 
, , 
AAAA, L2xL2y, truetrue
AA, L3x, false
BB, L3y, false

Try this instead:

private function lookForBBs(list:XMLList):void{
            for each (var x:XML in list){
                    if (x.@prop3 == "false"){
                            if (x.@prop1 == "BB"){
                                    t2.text += x.@prop2+"\n";
                            }       
                    }
                    else{
                            lookForBBs(x.children());
                    }
            }
    }
John Lemberger