数据库读取成xml格式(tree格式)

来源:互联网 发布:antlr解析源码 编辑:程序博客网 时间:2024/05/14 17:25

需要commons-collections-3.2.1.jar包

 

import org.apache.commons.collections.MultiHashMap;
import org.apache.commons.collections.MultiMap;

 

/**
     * @return String
     * @param
MultiMap

     *  @param id        

获得tree结构
     */

public static String getChild(MultiMap nodes,String id){
        StringBuffer sb = new StringBuffer();
        if(nodes.get(id) instanceof List){
            List<MenuInfo> list = (List)nodes.get(id);
            MenuInfo node = null;//VO实体类
            for(int i=0;i<list.size();i++){
                node = list.get(i);
                sb.append(""+getT("/t", node.getLevel())+"<node id='"+node.getMenuCode()+"' label='"+node.getMenuName()+"'>/n");//组装成xml结构
                if(nodes.get(node.getMenuCode()) instanceof List){
                    sb.append(getChild(nodes,node.getMenuCode()));
                }else{
                    sb.append("</node>/n");
                }
                if(i==list.size()-1)
                    sb.append("</node>/n");
            }
        }
        return sb.toString();
    }

 

/**
     * @return String
     * @param null
     *            获得tree结构
     */

    public String getMenuTree(String roleId){
        List list=this.queryAllMenu(roleId);//查询数据库返回集合
        MultiMap nodes = new MultiHashMap(list.size());
        MenuInfo node = null;
        for(Iterator<MenuInfo> it = list.iterator();it.hasNext();){
            node = (MenuInfo)it.next();
            nodes.put(node.getMenuParent(), node);
        }
       
        StringBuffer sb = new StringBuffer("<node id='-1'>/n");
        List<MenuInfo> lst1 = (List)nodes.get(0);
        sb.append(getChild(nodes,"-1"));
        return sb.toString();
    }

 

/**
     * @return List
     * @param roleId(权限代码)
     *            根据权限查询所有的菜单
     */

    public List queryAllMenu(String roleId) {
        String sql = "select m.* from U_MenuInfo m where m.MenuCode in(select r.menuId from U_RoleMenu r where r.roleId=?)";
        Connection con = SqlHelp.getConn();//SqlHelp自己写的链接数据库类
        PreparedStatement pst = null;
        ResultSet rs = null;
        List menus = new ArrayList();

        try {
            pst = con.prepareStatement(sql);
            pst.setString(1, roleId);
            rs = pst.executeQuery();
            while (rs.next()) {
                MenuInfo menu = getResult(rs);
                menus.add(menu);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            SqlHelp.colseConn(con, pst, rs);
        }
        return menus;
    }

 

/*生成结果如下*/

<node id="">

      <node id="" label="">

             <node id="" label="">

            </node>

      </node>

</node>