从数据库中读取记录集到平面式XML
发表于:2007-07-14来源:作者:点击数:
标签:
从 数据库 中读取记录集到平面式XML package jing.xml; /** * pTitle: 从数据库中读取记录集到平面式XML文件/p * pDescription: /p * pCopyright: Copyright (c) 2004/p * pCompany: /p * @author 欧朝敬 13873195792 * @version 1.0 */ //将数据库表输出为X
从
数据库中读取记录集到平面式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 ele
.netcol = 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 文档生成完毕!");
}
}
原文转自:http://www.ltesting.net