Using haxe.xml.Fast

While the base Xml API is easy to use, it is sometimes a bit painful to do all the checks of Xml correctness, and can result in verbose code. The haxe.xml.Fast API is here to help by providing a fast dot-syntax access to the most common Xml methods.

Here's an example of fast XML usage :

// parse some xml data
var xml = Xml.parse("
    <user name='john'>
        <phone>
            <number>0000</number>
            <number>111</number>
        </phone>
    </user>
");

// wrap the xml for fast access
var fast = new haxe.xml.Fast(xml.firstElement());

// access attributes
trace(fast.att.name); // attribute "name"
if( fast.has.age ) trace( fast.att.age ); // optional attribute

// access the "phone" child, which is wrapped with haxe.xml.Fast too
var phone = fast.node.phone;

// iterate over numbers
for( p in phone.nodes.number ) {
     trace(p.innerData);
}

This code works the same on all platforms.

Accessors

Here's the different accessors of the Fast API :

  • .name : returns the name of the current element (same as Xml.nodeName)
  • .x : returns the current corresponding Xml node.
  • .att.<name> : access to a given attribute. An exception is thrown if the attribute doesn't exists
  • .has.<name> : check the existence of an attribute
  • .elements : the list of all sub-elements (which are the nodes with type Xml.Element)
  • .node.<name> : access to the first sub element with the given name. An exception is thrown if the element doesn't exists.
  • .nodes.<name> : returns a List of elements with the given name
  • .hasNode.<name> : check the existence of a sub node with the given name
  • .innerData : returns the inner PCDATA or CDATA of the node. An exception is thrown if there is no data or if there not only data but also other nodes
  • .innerHTML : returns the XML string built with all the sub nodes, excluding the current one

Self-closed nodes

Please note that you cannot access self-closed nodes as "regular" ones. For example, provided this XML:

var xml = Xml.parse("
    <myNode1></myNode1>
    <myNode2/>
");

var fast = new haxe.xml.Fast(xml.firstElement());

var myNode1Value = fast.node.myNode1.innerData; // no problem
var myNode2Value = fast.node.myNode2.innerData; // ERROR, an exception is thrown!

In case your app might get self-closed nodes, check before:

var myNode2Value = (fast.node.myNode2.hasNode.innerData)? fast.node.myNode2.innerData : ""; // default to whatever value you want
version #4303, modified 2008-09-24 00:14:23 by zarate