示例如下:
public class DBtoXML {
private final String driver="com.mysql.jdbc.Driver";
private final String url="jdbc:mysql://localhost:3306/mysql";
private Connection connection=null;
public Connection getConn()
{
try {
Class.forName(driver);
connection = DriverManager.getConnection(url,"root","root");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
public boolean db_to_xml()
{
Connection conn=null;
Statement stm = null;
ResultSet rs=null;
conn = this.getConn();
Document doc = new Document();
Element rootElement = new Element("emps");
try {
stm = conn.createStatement();
rs= stm.executeQuery("select * from emp");
ResultSetMetaData mete = rs.getMetaData();
while (rs!=null&&rs.next()) {
Element element = new Element(mete.getColumnName(1));
element.setText(rs.getInt("eid")+"");
Element element2 = new Element(mete.getColumnName(2));
element2.setText(rs.getString("ename"));
Element element3 = new Element(mete.getColumnName(3));
element3.setText(rs.getString("sex"));
Element element4 = new Element(mete.getColumnName(4));
element4.setText(rs.getInt("age")+"");
Element element5 = new Element(mete.getColumnName(5));
element5.setText(rs.getString("job"));
rootElement.addContent(element);
rootElement.addContent(element2);
rootElement.addContent(element3);
rootElement.addContent(element4);
rootElement.addContent(element5);
}
doc.addContent(rootElement);
Format fromat =Format.getPrettyFormat();
fromat.setEncoding("gbk");
XMLOutputter out = new XMLOutputter(fromat);
out.output(doc, System.out);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
public static void main(String[] args) {
DBtoXML xmlBtoXML = new DBtoXML();
xmlBtoXML.db_to_xml();
}
}
JAVA实现将数据库数据转换成XML过程
最新推荐文章于 2022-07-25 14:33:29 发布