java查询数据库通过递归算法评带层级结构的xml
public static String initTreeMenu() {
// TODO Auto-generated method stub
Connection con=null;
ResultSet rs=null;
PreparedStatement pstmt=null;
StringBuffer sb=new StringBuffer();
try {
con=DBUtil.getInstance().getConnection();
String sql="select * from RESOURCENODE_INFO t where pid=0";
pstmt=(PreparedStatement) con.prepareStatement(sql);
rs=pstmt.executeQuery();
sb.append("<?xml version='1.0' encoding='utf-8'?>").append("<menu>");
while(rs.next()){
sb.append("<node id='"+rs.getInt("id")).append("' name='"+rs.getString("name")).append("'>");
if(rs.getInt("isResource")==0){
sb.append(tree(con,rs.getInt("id")));
}
sb.append("</node>");
}
sb.append("</menu>");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtil.getInstance().free(rs, pstmt, con);
}
return sb.toString();
}
public static String tree(Connection con,int id){
String sql="select * from RESOURCENODE_INFO t where t.pid = "+id;
StringBuffer sb=new StringBuffer();
try {
PreparedStatement pstmt=(PreparedStatement) con.prepareStatement(sql);
ResultSet rs=pstmt.executeQuery();
while(rs.next()){
sb.append("<node id='"+rs.getInt("id")).append("' name='"+rs.getString("name")).append("'/>");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
//测试函数
public static void main(String[] args) {
String sb=initTreeMenu();
System.out.println(sb);
}