日期:2014-05-16 浏览次数:20531 次
tree_id | tree_text | tree_pid | tree_action |
1 | 系统设置 | 0 | null |
2 | 用户设置 | 1 | user_action |
3 | 角色设置 | 1 | role_action |
4 | 权限设置 | 1 | privilege_action |
5 | 业务模块 | 0 | null |
6 | 销售管理 | 5 | sale_action |
package com.test; public class Tree { private String treeId; private String treeText; private String treePid; private String treeAction; public String getTreeId() { return treeId; } public void setTreeId(String treeId) { this.treeId = treeId; } public String getTreeText() { return treeText; } public void setTreeText(String treeText) { this.treeText = treeText; } public String getTreePid() { return treePid; } public void setTreePid(String treePid) { this.treePid = treePid; } public String getTreeAction() { return treeAction; } public void setTreeAction(String treeAction) { this.treeAction = treeAction; } }
创建一个类: public class TreeDAO(){ public List getTreeList(){ String sql = "select tree_id,tree_text,tree_pid,tree_action from tree_t order by tree_pid,tree_id"; //上面的关键点是order by tree_pid,tree_id,目的是使取出来的数据按照tree_pid的次序来排序。 //取数据的过程就不说了,网上一大堆,关键是要将所有取出来的装载到Tree对象中 Tree tree = null; //...遍历结果集 tree = new Tree(); tree.setTreeId(rs.getString("")); tree.setTreeText(rs.getString("")); tree.setTreePid(rs.getString("")); tree.setTreeAction(rs.getString("")); list.add(tree); //...结束遍历 return list; } }
import java.util.*; import org.dom4j.*; import org.dom4j.VisitorSupport; public class TreeBO extends VisitorSupport { private Tree tree; public Tree getTree() { return tree; } public void setTree(Tree tree) { this.tree = tree; } public void visit(Element element) { Tree t = this.getTree(); if (element.attributeValue("id").equals(t.getTreePid())) { Element e = element.addElement("item"); e.addAttribute("text", t.getTreeText()); e.addAttribute("id", t.getTreeId()); e.addAttribute("pid", t.getTreePid()); e.addAttribute("action",t.getTreeAction()); } } public void visit(Attribute attr) { } public String getTreeXml() { TreeDAO dao = new TreeDAO(); List list = dao.getTreeList(); Document document = DocumentHelper.createDocument(); Element root= document.addElement("tree").addAttribute("id", "0").addAttribute("radio", "0"); TreeBO bo = new TreeBO(); //遍历获得的list,每get(i)一个元素,遍历一次xml文件,看看当前元素的pid与xml文件的哪一个对应,对应的,则在这个父节点上挂子节点 for (int i = 0; i < list.size(); i++) { bo.setTree((Tree) list.get(i)); root.accept(bo);//利用dom4j的visitor模式进行xml文件的遍历 } return root.asXML();//最后生成xm