Search code examples
javascriptxmle4x

E4X - Retrieve element without retrieving its children


Given a XML object, how could I retrieve only the root element without retrieving together its children?

E.g.:

var exampleXml = new XML("<parent name="Teste"><child/><child2/><child3/></parent>");
exampleXml.getOnlyRootElement(); //<parent name="Teste"/>

I've found this solution - Flex e4x filter out children - but I didn't like it very much. Is there a better one?

PS: I'm running javascript in an windows app using SpiderMonkey.

Thanks


Solution

  • You can just set the child reference to an empty XMLList.

     exampleXML.setChildren(new XMLList(''));
    

    If you want to preserve the original XML object, make a deep copy first

     childFreeXML = exampleXML.copy().setChildren(new XMLList(''));