The incredible orphaned XML

It’s best to show an example on this mysterious AS3 quandary:

var demo:XML = <wrapper>
<child id=”element1″ />
<child id=”element2″ />
</wrapper> ;

var element1:Object = {} ;
var element2:Object = {};

// Create an object reference to each child node
element1.xmlRef = demo.children()[0];
element2.xmlRef = demo.children()[1];

// Now, remove the second node
delete demo.children()[1];

// This should be ‘null’ or ‘undefined’, or throw an RTE, right?!
trace(element2.xmlRef.toXMLString());

However, such is not the case.  While trace(demo.toXMLString()) shows the correct document structure, the trace line above shows that the node reference has now morphed into what I call “the incredible orphaned XML”. So, of course, the question becomes how to tell whether these nodes are ‘real’ nodes, or just an orphaned remnant.  The solution appears to be in childIndex().  The orphaned node returns a childIndex() of -1.  Yes, that’s right - it essentially doesn’t exist (we already knew that!). So, you have to check the childIndex(), and if it returns -1, then it’s a zombie XML node:

// This returns -1
trace(element2.xmlRef.childIndex());

As I write this post, a new question comes to mind… perhaps does that orphaned XML later get GC’d by the Garbage Collector, or is this a potential memory leak?  More investigations to come…


About this entry