简体   繁体   English

从xml创建树结构

[英]create tree structure from an xml

i have a XML like 我有一个像XML

<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 我想在jsp中创建一个显示为

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? 我将所有数据与xml的DOM对象一起使用,下一步如何进行?

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: 看来你需要一流的范畴与字段名称,FOLDERPATH等。另外它应该包含类别的集合:

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

Now use DOM API to iterate over nodes, create Category objects and add them to the parent. 现在,使用DOM API遍历节点,创建Category对象并将其添加到父级。 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. 或者,您可以实现递归方法,该方法将当前父元素作为参数接收DOM。

But why to do all this? 但是为什么要做所有这一切呢? Use higher level tools like Digester or JAXB that do everything you need almost for free! 使用Digester或JAXB之类的高级工具几乎可以免费完成您需要的一切!

Well, basically, you already have a tree with the DOM tree 好吧,基本上,您已经有了一棵包含DOM树的树

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 这就是您递归创建子树的方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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