I'm trying to use the delete keyword to remove nodes from an xml file and it just plain won't work.
Here's a stripped down example of what I'm working with. Every node has a child named "deleteme". If its value is equal to 1 I want to remove it from the xml file. If its anything else I want to leave it be. The delete method is deffinately gettig call but it's having no effect.
<?xml version="1.0" encoding="utf-8"?>
<stuff>
<i>
<deleteme>
0
</deleteme>
</i>
<i>
<deleteme>
1
</deleteme>
</i>
<i>
<deleteme>
0
</deleteme>
</i>
</stuff>
ActionScript
var xmlList:XMLList=_sourceXML.i;
for (var j:int=0; j < _xmlList.length(); j++)
{
if (xmlList[j].deleteme== 1)
{
delete xmlList[j];
}
}
//breakpoint here. xmlList still contains nodes that should have been deleted
xmlListColl=new XMLListCollection(xmlList);
xmlListColl.refresh()
Edit
If I trace the xmllist lenght before and after the delete for loop the length is indeed different. It seems for some reason the xmllist being passed to the xmllistcollection is the one with node not deleted. Makes no sense to me.
Edit 2
The following gives the desired result. I would still however like to know why the former method was not working.
for (var j:int=0; j < xmlList.length(); j++)
{
//trace(xmlList[j].deleteme)
if (xmlList[j].deleteme!=1 )
{
//delete xmlList[j];
xmlListColl.addItem(xmlList[j])
}
}
Yo
You need to do the 'for loop' in reverse. This goes for removing items in any collection/list via an iteration loop.
When an item is deleted (e.g. index 2 when j is 2), the next item in the List fills the space left by the deleted item (e.g. index 3 becmoes index 2), but j gets increased to 3, and the shifted item (in index 2) gets skipped. The following will work:
var _xmlList:XMLList=_sourceXML.i;
for (var j:int=_xmlList.length() - 1; j >= 0 ; j--)
{
if (_xmlList[j].deleteme == 1)
{
delete _xmlList[j];
}
}