ImportJava.io.FileOutputStream;Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement;ImportJavax.xml.parsers.DocumentBuilder;Importjavax.xml.parsers.DocumentBuilderFactory;ImportJavax.xml.transform.OutputKeys;ImportJavax.xml.transform.Transformer;Importjavax.xml.transform.TransformerFactory;ImportJavax.xml.transform.dom.DOMSource;ImportJavax.xml.transform.stream.StreamResult;Importorg.w3c.dom.Document;Importorg.w3c.dom.Element;/** @ Author Roger * @date 2016/5/3 * @description Enter the SQL statement to write the results to an XML file. The file format is formatted by the field name of the database, the field value. * */ Public classPxml { Public Static voidMain (String args[])throwsexception{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 ("Load MySQL driver successfully"); Conn=drivermanager.getconnection (URL); Statement stmt=conn.createstatement (); SQL= "SELECT * from people"; ResultSet RS=stmt.executequery (SQL); System.out.println ("Enquiry Personnel Information:"); 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 (NewDomsource (DOC),NewStreamresult (NewFileOutputStream ("D:\\sql.xml"));//perform the above settings and output to a fileSYSTEM.OUT.PRINTLN ("Generate XML file successfully!")); }Catch(Exception e) {e.printstacktrace (); } }Catch(SQLException e) {System.out.println ("MySQL Operation Error"); E.printstacktrace (); }Catch(Exception e) {e.printstacktrace (); }finally{conn.close (); } }}
Enter the SQL statement to write the result to the XML file