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")); //創(chuàng)建文檔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()); //格式華輸出,產(chǎn)生縮進(jìn)和換行
Format format = outp.getFormat();
format.setEncoding("UTF-8"); //設(shè)置語言
format.setExpandEmptyElements(true); //設(shè)置輸出空元素為<sample></sample>格式
outp.setFormat(format);
outp.output(document, new FileOutputStream("C:/ResultSet.xml")); //輸出XML文檔
System.out.print("XML 文檔生成完畢!");
} catch (Exception e) {
e.printStackTrace();
}
}
}