Search code examples
xmlactionscript-3e4x

Converting an XMLDocument to E4X in AS3?


I'm attempting to convert some AS2 XML code to E4X. I have the following code original XML (now XMLDocument) syntax below:

//temp var used to access createElement and creatTextNode 
var tempXML:XML = new XML(); 

//make an element:  <myNodeName> 
var myNode:XMLNode = tempXML.createElement("myNodeName"); 

//make a text node: "myValue" 
var myTextNode = tempXML.createTextNode("myValue"); 

//put the text node into the element: <myNodeName>myValue</myNodeName> 
myNode.appendChild( myTextNode ); 

//test it 
trace( myNode.toString() ); 

What would the equivalent be if I were to write it in E4X?

I'm specifically looking to reproduce the createElement() and createTextNode() functions in E4X.


Solution

  • Example:

        public function ASTest() 
        {
            var xmlDocument:String = testXMLDocument();
            var e4x:String = testE4X();
            trace("xmlDocument: "+xmlDocument);
            trace("e4x: "+e4x);
    
            trace("assert true: " + (xmlDocument == e4x));
        }
    
        public function testXMLDocument():String 
        {
            //temp var used to access createElement and creatTextNode 
            var tempXML:XMLDocument = new XMLDocument(); 
    
            //make an element:  <myNodeName> 
            var myNode:XMLNode = tempXML.createElement("myNodeName"); 
    
            //make a text node: "myValue" 
            var myTextNode:XMLNode = tempXML.createTextNode("myValue"); 
    
            //put the text node into the element: <myNodeName>myValue</myNodeName> 
            myNode.appendChild( myTextNode ); 
    
            //test it 
            return myNode.toString();       
        }
    
        public function testE4X():String 
        {
            //make an element:  <myNodeName> 
            var myNode:XML = <myNodeName />;
    
    
            /**
             * put the text node into the element: <myNodeName>myValue</myNodeName>
             * Two options to achieve that:
             *  1) using methods of XML class
             *  2) using e4k operators
             * Both ways give the same result
             */
    
            //1) XML function usage:
            //myNode.appendChild("myValue");
    
            //2) e4x syntax
            myNode.* += "myValue";
    
            //test it 
            return myNode.toXMLString();        
        }
    

    Output:

    xmlDocument: <myNodeName>myValue</myNodeName>
    e4x: <myNodeName>myValue</myNodeName>
    assert true: true