public class databasetoxml { public databasetoxml() { }
public static void main(String[] args) throws Exception { Class.forName("Oracle.jdbc.driver.OracleDriver").newInstance(); String url = "jdbc:oracle:thin:@192.168.128.250:1521:sample"; Connection conn = DriverManager.getConnection(url, "scott", "tiger"); PReparedStatement pstmt = conn.prepareStatement( "select * from company order by cid", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery(); Document document = new Document(new Element("ROOT")); //创建文档ROOT元素 ResultSetMetaData rmd = rs.getMetaData(); int colcount = rmd.getColumnCount(); Element elemnetcol = new Element("COLTYPE"); for (int i = 1; i <= colcount; i++) { //列属性 elemnetcol.setAttribute(rmd.getColumnName(i), rmd.getColumnTypeName(i)); } document.getRootElement().addContent(elemnetcol);
while (rs.next()) { //不确定表生成XML记录 Element element0 = new Element("ROW"); for (int i = 1; i <= colcount; i++) { element0.setAttribute(rmd.getColumnName(i),(rs.getString(i)==null?"":rs.getString(i))); } document.getRootElement().addContent(element0); } rs.close(); pstmt.close(); 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(document, new FileOutputStream("company.xml")); //输出XML文档 System.out.print("XML 文档生成完毕!"); } }