简体   繁体   中英

create tree structure from an xml

i have a XML like

<rootXml>
    <category id="1" name="Dept 1" folderPath="/css" leftHt="400"
        leftWd="50" rightHt="400" rightWd="50">
        <category id="2" name="Service 1" folderPath="/news/world"></category>
        <category id="3" name="Service 2" folderPath="/news/local"></category>
        <category id="4" name="Service 3" folderPath="/news/crime"></category>
        <category id="5" name="Service 4" folderPath="/news/humaninterest"></category>
    </category>
</rootXml>

i want to create a tree structure in jsp that displays like

Dept1 
   Service1
   Service2
   Service3
   Service4

basically on clicking parent node its child should be displayed..

i used dojo before but its quite heavy and want to develop it by my own code. i have the DOM object of the xml with me with all the data, how to proceed next?

Create data model (if you do not have it already). It seems that you need class Category with fields name, folderPath etc. Additionally it should contain collection of Category:

private Collection<Category> = new ArrayList<Category>();

Now use DOM API to iterate over nodes, create Category objects and add them to the parent. You should use stack-like structure: when you see the category tag create the object and add it to the stack. Then iterate over the internal tags. When you meet category tag create the object again, take the parent Category from the stack and add current category to the parent.

Alternatively you can implement recursive method that receives DOM the current parent element as arguments.

But why to do all this? Use higher level tools like Digester or JAXB that do everything you need almost for free!

Well, basically, you already have a tree with the DOM tree

If you want to have the structure in an array for instance, you should do it like this:

// lets say that obj is the <rootXml> object - the root of the tree

    function makeTree( obj ){
      var a = ob.childNodes;
      if(a.length == 0) return obj;

      var tree = [];
      for(var i in a){
        if(a.childNodes.length > 0) // if it has children -> it is a node
            tree.push( makeTree(a[i]) );
          else // it doesn't have any children -> it is a leaf
            tree.push( a[i] );
      }

      return tree;
    }

    var tree = makeTree( obj );

And that's how you create a child tree recursively

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM