I’m sure I missed something along the way, so please post a comment if you know how to do this better.

I needed to get a reference to the current node in ActionScript 3.0, but I also needed to exclude any and all elements, descendants, children, etc. . . . you know, just the one element, from left angled bracket to right angled bracket.  I needed the result to be it’s own XML object, too.  I had a hell of time figuring out how to do this, and my solution is (what I consider) a hack.

For example, if I have this XML object:

<obj id="203" name="TestObj" otherInfo="whatever">
    <inner id="443" name="innerObj" />
    <inner id="443" name="innerObj" />
    <inner id="443" name="innerObj" />
</obj>

I want to return only:

<obj id="203" name="TestObj" otherInfo="whatever" />

So, this is what I came up with that works.:

  1. Copy the element (which brings the kids along)
  2. Delete all the children (delete xml.*)

This leaves the node itself as an XML object.  Here is a chunk of code to do this:

// Whatever your original XML is:
var origXML:XMLList = <obj id="1"><childObj id="2"/><childObj id="3"/><childObj id="4"><innerChildObj id="5"/></child></obj>;

// Make a copy, so that the original is can be re-used.
var strippedXML:XML = new XML(origXML.copy());

// Remove everything which is not the root element.
delete strippedXML.*;

// This strippedXML can now be used elsewhere as an XML object.
var tempOtherXML = new XML(strippedXML.toXMLString());

// Prove that this worked correctly.
//trace("\t q = " + q.toXMLString());
//trace("\t origXML = " + origXML);

– 30 –

Advertisements