输入sql语句,将结果写入到xml文件
import java.io.FileOutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; /* * @ author Roger * @date 2016/5/3 * @description 输入sql语句,将结果写入到xml文件。文件格式按数据库的字段名,字段值格式。 * */ public class pXML { public static void main(String args[]) throws Exception{ Connection conn = null; String sql; String url = "jdbc:mysql://localhost:3306/test?" + "user=root&password=root&useUnicode=true&characterEncoding=UTF8"; try{ Class.forName("com.mysql.jdbc.Driver"); System.out.println("成功加载MySQL驱动程序"); conn = DriverManager.getConnection(url); Statement stmt = conn.createStatement(); sql = "select * from people"; ResultSet rs = stmt.executeQuery(sql); System.out.println("查询人员资料:"); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.newDocument(); Element root = doc.createElement("Info"); doc.appendChild(root); while(rs.next()){ Element people = doc.createElement("People"); System.out.println(rs.getString(1) + "\t" + rs.getString(2) + "\t" + rs.getString(3) + "\t" + rs.getString(4)); Element no = doc.createElement("no"); no.appendChild(doc.createTextNode(rs.getString(1))); people.appendChild(no); Element name = doc.createElement("name"); name.appendChild(doc.createTextNode(rs.getString(2))); people.appendChild(name); Element sex = doc.createElement("sex"); sex.appendChild(doc.createTextNode(rs.getString(3))); people.appendChild(sex); Element age = doc.createElement("age"); age.appendChild(doc.createTextNode(rs.getString(4))); people.appendChild(age); root.appendChild(people); } TransformerFactory tf = TransformerFactory.newInstance(); try{ Transformer t = tf.newTransformer(); t.setOutputProperty(OutputKeys.INDENT,"yes"); t.setOutputProperty(OutputKeys.METHOD,"xml"); t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2"); t.transform(new DOMSource(doc),new StreamResult(new FileOutputStream("d:\\sql.xml"))); //执行上面的设置并且输出到文件中 System.out.println("生成XML文件成功!"); }catch(Exception e){ e.printStackTrace(); } }catch(SQLException e){ System.out.println("MySql操作错误"); e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); }finally{ conn.close(); } } }