在AS3中将XMLDocument转换为E4X?

时间:2016-07-31 07:14:25

标签: xml actionscript-3 e4x

我正在尝试将一些AS2 XML代码转换为E4X。我在下面有以下代码原始XML(现在XMLDocument)语法:

//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() ); 

如果我在E4X中写它,它的等价物是什么?

我特意想要在E4X中重现createElement()createTextNode()函数。

2 个答案:

答案 0 :(得分:1)

var myNode = <myNodeName>myValue</myNodeName>就是你需要构建的字面意思。如果您将内容作为字符串变量,请使用var myNode = <myNodeName>{yourVariable}</myNodeName>

答案 1 :(得分:1)

示例:

    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();        
    }

输出:

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