利用xmlDoc读取xml文件构建ExtJS Tree
???? ExtJS的Tree控件利用TreeNode构建内置的数据,在client/Server的结构中,利用TreeLoader从server端获得Tree中的数据,最终显示。在实际的生产环境中,大量的情况是用TreeLoader来获得这些数据,数据的默认格式是Json格式。在实际的生产中,有时利用xml作为数据源,在ExtJS自带的例子中,有XMLTreeLoader的例子,扩展TreeLoader,实现xml格式数据的加载,但是,当不利用server时,则无法加载xml的数据源。
????? 下面通过利用xmlDoc加载本地的xml文件(也可以通过XMLHttpRequest加载远程的xml),进行ExtJS的tree构建。?
首先是定义要加载的xml文件:book.xml如下:
<?xml version="1.0" encoding="UTF-8"?><bookstore> <book category="children"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="web" cover="paperback"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> <book category="web"> <title lang="en">XQuery Kick Start</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book></bookstore>
?? 通过xmlDoc加载book.xml文件,在html文档中,形成xmlDoc对象:
function loadXMLDoc(dname){try //Internet Explorer { xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); }catch(e) { try //Firefox, Mozilla, Opera, etc. { xmlDoc=document.implementation.createDocument("","",null); } catch(e) {alert(e.message)} }try { xmlDoc.async=false; xmlDoc.load(dname); return(xmlDoc); }catch(e) {alert(e.message)}return(null);}
?然后再Ext.onReady函数中构建整个tree的结构并显示:
Ext.onReady(function() {xmlDoc = loadXMLDoc("book.xml");x = xmlDoc.documentElement.childNodes;var rootNode = new Ext.tree.TreeNode( { // 1text : "bookStore",expanded : true});for (i = 0; i < x.length; i++) {if (x[i].nodeType == 1) {var child = new Ext.tree.TreeNode({text:x[i].getAttributeNode("category").nodeValue,expanded:true});rootNode.appendChild(child);y = x[i].childNodes;for (j = 0; j < y.length; j++) {if (y[j].nodeType == 1) {var gradonson = new Ext.tree.TreeNode({text:y[j].childNodes[0].nodeValue,leaf:true});child.appendChild(gradonson);}}}}var tree = {title : 'tree',width : '12%',region : 'west',xtype : 'treepanel',autoScroll : true,root : rootNode};var panel2 = {region : 'center',title : 'Plain Panel 2',html : 'Panel with __tag_27$24_no__tag_27$29_ xtype specified'};new Ext.Viewport( {layout : 'border',items : [ tree, panel2 ]});});
?
就可以生成利用xml文件定义的ExtJS Tree了。
谢谢 终于找到一个可以跑得通的了