Search code examples
xmljsonextjstreetreepanel

How to get JSON or XML from parsed Ext js Tree?


I have Tree, loaded from XML exactly like this.

Additionally I enable drag and drop. Now after making changes in tree by drag and drop, we should be able to get new data so that I can generate new xml.

Even JSON would help to re-generate new xml.


Solution

  • function getJson(treeNode) {
        treeNode.expandChildNodes();
        var json = {};
        var attributes = treeNode.attributes;
        for(var item in attributes){
            if (item == 'src' || item == 'text') {   //only use required attributes
                json[item] = attributes[item];
            }
        }
        json.children = [];
        if(treeNode.childNodes.length > 0){
            for (var i=0; i < treeNode.childNodes.length; i++) {
                json.children.push(getJson(treeNode.childNodes[i]));
            }
        }
        return json;
    }
    
    // To use above function:
    var comp = Ext.getCmp('tree-panel'); //id of the tree panel
    var myJSON = getJson(comp.getRootNode());
    console.log(Ext.encode(myJSON.children));
    

    Can't think about creating XML. I'll make it on server side..

    Hope someone could also work on it.