1.21 gigawatts
1.21 gigawatts

Reputation: 17820

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.

Upvotes: 0

Views: 64

Answers (2)

fsbmain
fsbmain

Reputation: 5267

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

Upvotes: 1

Martin Honnen
Martin Honnen

Reputation: 167696

var myNode = <myNodeName>myValue</myNodeName> is all you need to construct that literally. If you have the contents as a string variable then use var myNode = <myNodeName>{yourVariable}</myNodeName>.

Upvotes: 2

Related Questions