Using Xml

Creating a root element

A xml root element can be created either by using the Xml.createElement method
    var root = Xml.createElement('root');
    trace(root); // <root />

or by parsing a string containing the root element information:

    var root = Xml.parse('<root />').firstElement();
    trace(root); // <root />

Creating a child element

Adding a child element to the root can be done using the createElement method:
    var child:Xml = Xml.createElement('child'); 
    trace(root); // <root><child/></root>

Adding an attribute to an element is done by using the set() method:

    child.set('name', 'John');
    trace(root); // <root><child name="John"/></root>

Accessing elements and values

This code parses an XML string str into an object structure xml, and then accesses properties of the object to build a new string out :
    var str = '<hello name="world!">Haxe rules!</hello>';
    var xml : Xml = Xml.parse(str).firstElement();
    trace(xml.nodeName); // hello
    trace(xml.get('name')); // world!
    trace(xml.firstChild().nodeValue); // Haxe rules!

The difference between firstChild and firstElement is that the second function will return the first child with the type Xml.Element. You can as well use other methods to iterator either over children or elements :

    for( child in xml ) {
        // iterate all childs
    for( elt in xml.elements() ) {
        // iterate all elements
    for( user in xml.elementsNamed("user") ) {
        // iterate all elements with a nodeName "user" 
    for( att in xml.attributes() ) {
        // iterator over all attributes

You can read the Xml API for complete documentation.

version #13908, modified 2012-05-07 13:50:41 by cambiata