Conditionally remove multiple XML nodes in a loop?

XML.removeNode was removed for AS3s E4x, and now one simply uses delete (more).

Let's say I've got the following xml:

XML:
  1. <items>
  2.     <item>a</item>
  3.     <item>b</item>
  4.     <item>c</item>
  5.     <item>d</item>
  6.     <item>b</item>
  7.     <item>f</item>
  8. </items>

I'd like to delete all child nodes which do not have their node value set to "b". (there's two of them in that snippet).

Using a "for loop" and deleting items like : delete my_xml.item[i] fails, because the "array index" of nodes change as items are deleted (see code below).

No problem, just create a reference of the node, and delete it later:

var delete_later:XML=my_xml.item[i];

...but no, teh FAIL has come to visit you again! "delete_later" is not a reference to the node, it's just a placeholder for the value of that node. For the stubborn, trying to delete "delete_later" results in an error : "Attempt to delete the fixed property delete_later. Only dynamically defined properties can be deleted."

So what to do, what to do?

Simple, just loop through the array backwards! :ooh:

Here's my test code:

Actionscript:
  1. var list:XML=   <items>
  2.                     <item>a</item>
  3.                     <item>b</item>
  4.                     <item>c</item>
  5.                     <item>d</item>
  6.                     <item>b</item>
  7.                     <item>f</item>
  8.                 </items>;
  9.                
  10. var test1:XML=list.copy();
  11. for(var i:int=0;i<test1.item.length();i++){
  12.     if(test1.item[i]!="b")delete test1.item[i]
  13. }
  14. trace(test1);
  15. /*
  16. traces:
  17. <items>
  18.   <item>b</item>
  19.   <item>d</item>
  20.   <item>b</item>
  21. </items>
  22. //NOT SO GOOD AL... NOT SO GOOD...
  23. */
  24.  
  25.  
  26. var test2:XML=list.copy();
  27. for(i=test2.item.length()-1;i>-1;i--){
  28.     if(test2.item[i]!="b")delete test2.item[i]
  29. }
  30. trace(test2);
  31. /*
  32. traces:
  33. <items>
  34.   <item>b</item>
  35.   <item>b</item>
  36. </items>
  37. //WHOOOMP THERE IT IS!
  38. */

Tags: , ,

Leave a Reply