Sunday, January 30, 2011

Create a Treeview from a external XML file using JStree JQuery Plugin

Hi there,
I will show you how you can create a treeview using the jstree plugin by feeding it with external XML file. I have created the following XML file. Named Book.xml.


 Then after creating the xml file download the jstree plugin from here.
Then you need to create a Javascript file named "UIMTreeProcessor.js" with the following code:

function UIMTreeProcessor(data, treeEl) {
 this.data = data;
 this.treeEl = treeEl;
}
 
UIMTreeProcessor.prototype.initTree = function(data){
 this.treeEl.jstree({
  "json_data" : {
   "data":data,
   "progressive_render":"true"
  },
  "plugins" : [ "themes", "ui", "json_data" ],
  "core":{"animation":0}
  });
}
 
UIMTreeProcessor.prototype.doProcess = function(){
 //Find root:
 var _root = $(this.data).children(':first-child');
 var _a_feed = new Array();
 
 this.vsTraverse($(_root), _a_feed);
 
 var _treedata = [{"data":_root[0].nodeName,"children":_a_feed, "state":"open"}];
 this.initTree(_treedata);
}
 
UIMTreeProcessor.prototype.vsTraverse = function(node, arr){
 var _ch = $(node).children();
 
 for(var i=0; i<_ch.length; i++){
  var _vsArr = new Array();
  this.vsTraverse(_ch[i], _vsArr);
  var _a_att = this.vsTraverseAtt(_ch[i]);
  if(null!=_a_att){
   _vsArr.push([{"data":"Attributes "+"["+_ch[i].nodeName+"]","children":_a_att, attr : { "class" : "uim_attr"}}]);
  }
  if(null!=_ch[i].firstChild && 3==_ch[i].firstChild.nodeType){
   arr.push([{"data":_ch[i].nodeName + ": " + _ch[i].firstChild.textContent,"children":_vsArr, "state":"open"}]);
  }else{
   arr.push([{"data":_ch[i].nodeName,"children":_vsArr, "state":"open"}]);
  }
 
 }
}
 
UIMTreeProcessor.prototype.vsTraverseAtt = function(node){
 var _a_atts = null;
 if(null!=node.attributes && node.attributes.length > 0){
  _a_atts = new Array();
  for(var i=0; i<node.attributes.length; i++){
   _a_atts.push(node.attributes[i].nodeName + ":" + node.attributes[i].nodeValue);
  }
 }
 return _a_atts;
}

Then you need to add reference to all the scripts in your html/ASP.NET code beside.
 After that add the following code in the script section of your HTML page.


var _url = "example_01.xml";
  var _uimTree = null;
 
  $(function () {
   getTopContent();
  });
 
  getTopContent = function(){
   $.ajax({
    type: "GET",
    url: _url,
    dataType:"xml",
    cache: false,
    beforeSend:function(){
     //do something before send
    },
    success: function(data){
     processXML(data);
    },
    error:function(e){
     alert("Error: "+e);
    }
   });
  }  
 
  processXML = function(root){
   _uimTree = new UIMTreeProcessor(root, $("#jstree"));
   _uimTree.doProcess();
  }

Then add the following Div sectionin your HTML page:
div id="jstree" style="height:500px; overflow-y:auto;" class="ui-corner-all ui-widget-content"></div>
Here is how it would look like:

Now you are done...Njoy..
You can check the complete post with download links here: