/**
* Copyright leichtgewicht ( http://wonderfl.net/user/leichtgewicht )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/w7JL
*/
package {
import flash.text.TextField;
import flash.display.Sprite;
public class MovingXMLNodes extends Sprite {
public function MovingXMLNodes() {
var textField: TextField = new TextField();
textField.height = stage.stageHeight;
textField.width = stage.stageWidth;
addChild( textField );
var xml: XML = <test>
<a/>
<b/>
<b/>
<c-will-not-be-moved>
<d>
<e-moved-as-child/>
<f-moved-as-child/>
</d>
</c-will-not-be-moved>
<container>
<another-container>
<output>
<already-child />
</output>
</another-container>
</container>
</test>;
moveToNode( xml..output[0],
xml..a + // a single node
xml..b + // Multiple nodes
xml..d + // A node with children
xml + // the root - may not be added
xml.parent + // a parent that contains another parent
xml..anotherparent + // a direct parent of the output
<new-entry/> // entry from a different xml
);
textField.text = xml;
}
}
}
/**
* Moves node from a xml selection to another node.
*
* @param target Target XML node to receive the nodes in the list
* @param nodes Nodes to be moved to this list
* @param before Node before which the nodes should be added
* @param the last added node
**/
function moveToNode( target: XML, nodes: XMLList, before: XML = null ): XML {
// We need to iterate backwards because "delete nodes[i]" will change the nodes list
// No: "for each" doesn't work!
for( var i: int = nodes.length()-1; i>-1; --i) {
// The child is marked * because it can be XML or XMLList!
var child: * = nodes[i];
if( child is XMLList ) {
before = moveToNode( target, child, before );
} else {
// Check that the node is not a parent of this node
var isParent: Boolean = false;
var parent: XML = target.parent();
while( parent ) {
if( parent == child ) {
isParent = true;
break;
}
parent = parent.parent();
}
if( !isParent ) {
// Just add it once you made sure its addable
delete nodes[i];
if( before ) {
target.insertChildBefore( before, child );
} else {
target.appendChild( child );
}
before = child;
}
}
}
return before;
}