xml nodes will not delete despite calling “delete”

南楼画角 提交于 2019-12-30 14:50:13

问题


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])

                    }

                }

回答1:


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];                     
    }                   
}


来源:https://stackoverflow.com/questions/4946007/xml-nodes-will-not-delete-despite-calling-delete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!