import org.jdom.*;
import org.jdom.output.*;
import java.sql.*;
import java.io.*;
public class GenerateXMLView {
/** Creates a new instance of GenerateXMLView */
public GenerateXMLView() {
}
public static void main(String[] args) throws Exception {
WriteXMLtoFile();
}
public static void WriteXMLtoFile()
{
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
String dbName="/derby/demo/databases/toursdb";
String connectionURL = "jdbc:derby:" + dbName;
Connection conn = null;
Statement st = null;
ResultSet rs = null;
ResultSetMetaData rmd = null;
try{
Class.forName(driver);
} catch(java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(connectionURL);
st=conn.createStatement();
rs=st.executeQuery("SELECT distinct COUNTRY,CITY_NAME,AIRPORT FROM cities order by COUNTRY,CITY_NAME");
rmd = rs.getMetaData();
Document document = new Document(new Element("ResultSet")); //创建文档ROOT元素
document.getRootElement().setAttribute("type", "sleep");
int colcount = rmd.getColumnCount();
while (rs.next()) {
Element RowElement = new Element("DataRow");
RowElement.setAttribute("size", "XXXLarge");
for (int i = 1; i <= colcount; i++) {
Element TempElement=new Element(rmd.getColumnName(i).toString().toLowerCase());
//TempElement.setText(rs.getString(i));
TempElement.setAttribute("name",rmd.getColumnName(i).toString().toLowerCase());
TempElement.setAttribute("value",rs.getString(i));
TempElement.addContent(rs.getString(i));
RowElement.addContent(TempElement);
}
document.getRootElement().addContent(RowElement);
Element RowElement2 = new Element("ShowRow");
RowElement2.setText("Just For Show");
document.getRootElement().addContent(RowElement2);
Element Contact = new Element("Contact").setText("tel");
document.getRootElement().addContent(Contact);
}
rs.close();
st.close();
conn.close();
XMLOutputter outp = new XMLOutputter(Format.getPrettyFormat()); //格式华输出,产生缩进和换行
Format format = outp.getFormat();
format.setEncoding("UTF-8"); //设置语言
format.setExpandEmptyElements(true); //设置输出空元素为<sample></sample>格式
outp.setFormat(format);
outp.output(document, new FileOutputStream("C:/ResultSet.xml")); //输出XML文档
System.out.print("XML 文档生成完毕!");
} catch (Exception e) {
e.printStackTrace();
}
}
}