使用JDOM操作XML系列文章二 从数据库中读取记录集到平面式XML文
2008-01-05 08:41:42 来源:WEB开发网核心提示:使用JDOM操作xml系列文章二 从数据库中读取记录集到平面式XML文件package jing.xml;/** * <p>Title: 从数据库中读取记录集到平面式XML文件</p> * <p>Description: </p> * <p>Copyrigh
使用JDOM操作xml系列文章二 从数据库中读取记录集到平面式XML文件
package jing.xml;
/**
* <p>Title: 从数据库中读取记录集到平面式XML文件</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author 欧朝敬 13873195792
* @version 1.0
*/
//将数据库表输出为XML文档
import org.jdom.*;
import org.jdom.output.*;
import java.sql.*;
import java.io.*;
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 文档生成完毕!");
}
}
更多精彩
赞助商链接