English Japanese Kawa.netxp [JavaScript] XML.ObjTree - XML source code from/to JavaScript object like E4X

XML.ObjTree class is a parser/generater for XML source code and JavaScript object. This is a JavaScript version of XML::TreePP for Perl.
This also works as a wrapper for XMLHTTPRequest and successor to JKL.ParseXML class when using with prototype.js or JSAN's HTTP.Request class.
Attributes' prefix '@' like E4X (ECMAScript for XML) is also available.
Safari for Intel Mac is supported.

XML.ObjTree Group is now opened on Yahoo! Groups.

Download and Usage

Download from JSAN or links below:

Archive: XML.ObjTree-0.24.tar.gz TARGZ
.js source code only: lib/XML/ObjTree.js JavaScript
Document: README README Changes Changes

This class is tested on IE 7, Firefox 1.5.0, Opera 8.53 and Safari 2.0.3.

Static Loading by <script> Element

Static loading by <script> element. DEMO

<html>
<head>
<script src="lib/XML/ObjTree.js"></script>
</head>
<body>
<script><!--
    var xotree = new XML.ObjTree();
    var xml = '<?xml version="1.0"?><root><node>Hello, World!</node></root>';
    var tree = xotree.parseXML( xml );       	// source to tree
    document.write( "message: "+tree.root.node );
// --></script>
</body>
</html>

Dynamic Loading by JSAN.use() method

Dynamic Loading by JSAN.use() method. DEMO

<html>
<head>
<script src="lib/JSAN.js"></script>
</head>
<body>
<script><!--
    JSAN.addRepository("lib");
    JSAN.errorLevel = "die";
    JSAN.use( 'XML.ObjTree' );

    var xotree = new XML.ObjTree();
    var tree = {
        root: {
            node: "Hello, World!"
        }
    };
    var xml = xotree.writeXML( tree );        // tree to source
	xml = xml.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
    document.write( "xml: "+xml );
// --></script>
</body>
</html>

I prefer <script> element's way which is simple and fast.

JavaScript Object Mapping

A sample XML source:


<?xml version="1.0" encoding="UTF-8"?>
<family name="Kawasaki">
    <father>Yasuhisa</father>
    <mother>Chizuko</mother>
    <children>
        <girl>Shiori</girl>
        <boy>Yusuke</boy>
        <boy>Kairi</boy>
    </children>
</family>

Its JavaScript object tree:

{
    'family': {
        '-name':    'Kawasaki',
        'father':   'Yasuhisa',
        'mother':   'Chizuko',
        'children': {
            'girl': 'Shiori'
            'boy': [
                'Yusuke',
                'Kairi'
            ]
        }
    }
};

Each elements are parsed into objects:

tree.family.father;             # the father's given name.

Prefix '-' is added on every attributes' name.

tree.family["-name"];           # this family's family name

A array is used because this family has two boys.

tree.family.children.boy[0];    # first boy's name
tree.family.children.boy[1];    # second boy's name
tree.family.children.girl;      # (girl has no other sisiters)

Constructor and Methods

  xotree = new XML.ObjTree()

This constructor method returns a new XML.ObjTree object.

force_array Property

  xotree.force_array = [ "rdf:li", "item", "-xmlns" ];

This property allows you to specify a list of element names which should always be forced into an array representation. The default value is null, it means that context of the elements will determine to make array or to keep it scalar.

attr_prefix Property

  xotree.attr_prefix = '@';

This property allows you to specify a prefix character which is inserted before each attribute names. Instead of default prefix '-', E4X-style prefix '@' is also available. The default character is '-'. Or set '@' to access attribute values like E4X, ECMAScript for XML. The length of attr_prefix must be just one character and not be empty.

parseXML() Method

  tree = xotree.parseXML( xmlsrc );

This method loads an XML document using the supplied string and returns its JavaScript object converted.

This method uses ActiveX's XMLDOM (DOMDocument) object for IE or DOMParse object for Firefox to parse XML source code into DOM tree.

parseDOM() Method

  tree = xotree.parseDOM( domnode );

This method parses a DOM tree (ex. responseXML.documentElement) and returns its JavaScript object converted.

In fact, HTML page itself is a DOM tree as well.
I don't like Opera's behavior which changes every HTML attributes as upper case, like title="" as TITLE="".

parseHTTP() Method (Synchronous Mode)

  tree = xotree.parseHTTP( url, options );

This method loads a XML file from remote web server and returns its JavaScript object converted. XMLHTTPRequest's synchronous mode is used. This mode blocks the process until the response is completed.

First argument is a XML file's URL which must exist in the same domain as parent HTML file's. Cross-domain loading is not available for security reasons.

Second argument is options' object which can contains some parameters: method, postBody, parameters, onLoading, etc.

This method requires JSAN's HTTP.Request class or prototype.js's Ajax.Request class.

In many cases, asynchronous mode below is better way for users' experiences.

parseHTTP() Method (Asynchronous Mode)

  xotree.parseHTTP( url, options, callback );

If a callback function is set as third argument, XMLHTTPRequest's asynchronous mode is used.

This mode calls a callback function with XML file's JavaScript object converted after the response is completed.

writeXML() Method

  xmlsrc = xotree.writeXML( tree );

This method parses a JavaScript object tree and returns its XML source generated.

Examples

Text node and attributes

If a element has both of a text node and attributes or both of a text node and other child nodes, text node's value is moved to a special node named "#text".

var xotree = new XML.ObjTree();
var xmlsrc = '<span class="author">Kawasaki Yusuke</span>';
var tree = xotree.parseXML( xmlsrc );
var class = tree.span["-class"];        # attribute
var name  = tree.span["#text"];         # text node

parseHTTP() method with HTTP-GET and sync-mode

HTTP/Request.js or prototype.js must be loaded before calling this method.

var xotree = new XML.ObjTree();
var url = "http://example.com/index.html";
var tree = xotree.parseHTTP( url );
alert( tree.html["-lang"] );

This code shows index.html's lang="" attribute.

parseHTTP() method with HTTP-POST and async-mode

Third argument is a callback function which is called on onComplete.

var xotree = new XML.ObjTree();
var url = "http://example.com/mt-tb.cgi";
var opts = {
    postBody:   "title=...&excerpt=...&url=...&blog_name=..."
};
var func = function ( tree ) {
    alert( tree.response.error );
};
xotree.parseHTTP( url, opts, func );

This code send a trackback ping and shows its response code.

Simple RSS reader

This is a RSS reader which loads RDF file and displays all items.

var xotree = new XML.ObjTree();
xotree.force_array = [ "rdf:li", "item" ];
var url = "http://example.com/news-rdf.xml";
var func = function( tree ) {
    var elem = document.getElementById("rss_here");
    for( var i=0; i<tree["rdf:RDF"].item.length; i++ ) {
        var divtag = document.createElement( "div" );
        var atag = document.createElement( "a" );
        atag.href = tree["rdf:RDF"].item[i].link;
        var title = tree["rdf:RDF"].item[i].title;
        var tnode = document.createTextNode( title );
        atag.appendChild( tnode );
        divtag.appendChild( atag );
        elem.appendChild( divtag );
    }
};
xotree.parseHTTP( url, {}, func );

XML-RPC using writeXML, prototype.js and parseDOM

If you wish to use prototype.js's Ajax.Request class by yourself:

var xotree = new XML.ObjTree();
var reqtree = {
    methodCall: {
        methodName: "weblogUpdates.ping",
        params: {
            param: [
                { value: "Kawa.net xp top page" },  // 1st param
                { value: "http://www.kawa.net/" }   // 2nd param
            ]
        }
    }
};
var reqxml = xotree.writeXML( reqtree );       // JS-Object to XML code
var url = "http://example.com/xmlrpc";
var func = function( req ) {
    var resdom = req.responseXML.documentElement;
    xotree.force_array = [ "member" ];
    var restree = xotree.parseDOM( resdom );   // XML-DOM to JS-Object
    alert( restree.methodResponse.params.param.value.struct.member[0].value.string );
};
var opt = {
    method:         "post",
    postBody:       reqxml,
    asynchronous:   true,
    onComplete:     func
};
new Ajax.Request( url, opt );

Compare to JKL.ParseXML

XML.ObjTree class is a successor to JKL.ParseXML class (jkl-parsexml.js).
JKL.ParseXML contains wapper routine for XMLHTTPRequest which uses sometimes Microsoft.XMLDOM (DOMDocument) on IE to avoid "Content-Type: problem".

XML.ObjTree classJKL.ParseXML class
First Release2006/Apr/062005/May/18
Dependencies HTTP.Request class or prototype.js is required only for parseHTTP() method.
No libraries are required for other methods.
Only JKL.ParseXML itself is needed.
Any other libraries are NOT required
XML source code to JavaScript object OK - parseXML() method N/A
DOM Tree to JavaScript object OK - parseDOM() method OK parseDocument() method
Remote XML file to JavaScript object OK - parseHTTP() method OK - parse() method (main function)
JavaScript Object to XML source code OK - writeXML() method N/A
Other formats to JavaScript Object N/A OK - subclasses
Content-Type: application/rdf+xml ? - depend on browser OK - supported

Comments by AjaxCom

Links

Kawa.netxp © Copyright 2006 Yusuke Kawasaki