public class dBToxmltree { public String url = null; public Connection conn = null; public Document document = null; public dbtoxmltree() throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); url = "jdbc:oracle:thin:@192.168.128.250:1521:sample"; conn = DriverManager.getConnection(url, "scott", "tiger"); }
public void digui(int pid,Element element) throws Exception { String sql = "select * from company where pid=" + pid; PReparedStatement pstmt = conn.prepareStatement( sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery(); ResultSetMetaData rmd = rs.getMetaData(); int colcount = rmd.getColumnCount(); while (rs.next()) { Element element0 = new Element("DSTree"); for(int i=1;i<=colcount;i++){ element0.setAttribute(rmd.getColumnName(i), (rs.getString(i) == null ? "" : rs.getString(i))); } element0.setAttribute("open","false"); element.addContent(element0); digui(rs.getInt("CID"),element0); } rs.close(); pstmt.close();
}
public static void main(String[] args) throws Exception { dbtoxmltree dbxml = new dbtoxmltree(); Element root=new Element("DSTreeRoot"); dbxml.document=new Document(root);//创建文档ROOT元素 PreparedStatement pstmt = dbxml.conn.prepareStatement( "select * from company order by cid", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery();
ResultSetMetaData rmd = rs.getMetaData(); int colcount = rmd.getColumnCount(); Element elementcol = new Element("COLTYPE"); for (int i = 1; i <= colcount; i++) { //列属性 elementcol.setAttribute(rmd.getColumnName(i), rmd.getColumnTypeName(i)); } root.addContent(elementcol); rs.close(); pstmt.close();
dbxml.digui(0,root);
dbxml.conn.close(); XMLOutputter outp = new XMLOutputter(Format.getPrettyFormat()); //格式华输出,产生缩进和换行 Format format = outp.getFormat(); format.setEncoding("GB2312"); //设置语言 format.setEXPandEmptyElements(true); //设置输出空元素为<sample></sample>格式 outp.setFormat(format);
outp.output(dbxml.document, new FileOutputStream("companytree.xml")); //输出XML文档