I am working with XML in ActionScript and trying to find a way to remove a node by providing the node reference.
Sample:
var node:XML =
<node>
<child a="1" b="2" c="3" />
<child a="2" b="2" c="3" />
<child a="3" b="4" c="3" />
<child a="4" b="2" c="6" />
</node>;
var targetChild:Xml = node.child.@(a==1)[0];
Currently, I am using the following to accomplish the removal of the node. Also I prefer not to iterate through the tree again or filter the nodes to find the targetChild i have a开发者_如何转开发lready referenced.
delete (targetChild.parent().children()[targetChild.childIndex()]);
Somehow I just do not feel like it is a very clean way of doing it, but it works. I am wondering if there is another way to delete the node by reference?
two ways two delete by reference:
package {
/**
* ...
* @author www0z0k
*/
import flash.text.TextField;
import flash.display.Sprite;
import flash.text.TextFieldAutoSize;
public class FlashTest extends Sprite {
private var tf:TextField;
public function FlashTest() {
tf = new TextField();
addChild(tf);
tf.multiline = true;
tf.autoSize = TextFieldAutoSize.LEFT;
var node:XML = new XML('<node><child a="1" b="2" c="3"/><child a="2" b="2" c="3"/><child a="3" b="4" c="3"/><child a="4" b="2" c="6"/></node>');
tf.appendText('before:\n' + node);
var xml1:XML = node.descendants('child').(@a == '3')[0];
var xml3:XML = node.descendants('child').(@a == '1')[0];
killXMLFromList(xml1, node.descendants(xml1.name()));
delete node.descendants(xml3.name()).(@a == xml3.attribute('a'))[0];
tf.appendText('\nafter:\n' + node);
}
private function killXMLFromList(xml:XML, list:XMLList):void{
for (var i:int = 0; i < list.length(); i++ ) {
if (list[i] == xml) {
delete list[i];
}
}
}
}
}
精彩评论