|
This tutorial is for all those who are not famliar with the AS3 XML Object. I will start right at the beginning. Lets create an XML.
Creation / Instantiation
Within ActionScript you can create a XML Object using following Syntax. All of the three following Examples produce the same XML.
var myXML1:XML = new XML(<myNode/>);
var myXML2:XML = <myNode/>;
var myXML3:XML = XML('<myNode/>');
The resulting XML looks like this in all three cases. Better don't use the third variant, it is not necessary to quote XML syntax using ActionScript 3.
It is also possible to create a XML without specifing a root node. This will generate something that behaves like an empty XML-Document. You can't set a node name and appending Children is not possible either.
var myOtherXML:XML = new XML();
trace(myOtherXML.name()); // null
myOtherXML.setName("myNode");
trace(myOtherXML.name()); // still null
Appending and Deleting nodes
Step 1
Appending a node to a XML is quite easy. Just use the appendChild() method to add a node to the hierarchy.
var myFruits:XML = <fruits/>;
myFruits.appendChild(<apple/>);
trace(myFruits.toXMLString()); // toXMLString() prints a XML including the current rootNode.
The result will look like this. A simple XML.
<fruits>
<apple/>
</fruits>
Step 2
Now lets add some further nodes. You can use the prependChild() method to add a node at the first position. The inserChildAfter() and insertChildBefore() methods are use to add a node at a position before or behind a specified node in the XML. You need to navigate through the XML, in order to specify a node. In this example I used the dot syntax. Navigation within the XML Structure is another topic of this tutorial.
myFruits.prependChild(<banana/>);
myFruits.insertChildAfter(myFruits.banana,<melon/>);
myFruits.insertChildBefore(myFruits.melon,<strawberry/>);
trace(myFruits.toXMLString());
Now our XML looks like this. Notice the position of the new nodes added.
<fruits>
<banana/>
<strawberry/>
<melon/>
<apple/>
</fruits>
Step 3
Now let's clean up the mess. Deleting nodes. You can simply get rid of XML Nodes by using the delete operator.
delete myFruits.apple;
delete myFruits.children()[0]; // The first child of myXML
trace(myFruits.toXMLString());
The XML will now look like this. The first node and the last node are gone for ever.
<fruits>
<strawberry/>
<melon/>
</fruits>
Step 4
After we have cleaned up a little we add further nodes to the XML. You can also create new nodes by simply typing the path in dot-syntax. Another useful option is to use the setChildren() method. But beware it ovewrites existing nodes.
myFruits.passionFruit.granadilla= new XML();
var yourFruits:XML = <fruits><waterMelon/><honeydewMelon/></fruits>;
myFruits.melon.setChildren(yourFruits.children()); // adds only the children
trace(myFruits.toXMLString());
The final XML. Quite a lot nodes.
<fruits>
<strawberry/>
<melon>
<waterMelon/>
<honeydewMelon/>
</melon>
<passionFruit>
<granadilla/>
</passionFruit>
</fruits>
|