日期:2014-05-16 浏览次数:20407 次
package zrj.xml; import java.sql.*; import javax.xml.parsers.*; import org.w3c.dom.*; public class XMLToSQL { static Connection con; static String ICDM0a00,ICDM0a01,ICDM0a02,ICDM0a03,ICDM0a04,ICDM0a05,ICDM0a06,sql; public static void main(String args[]) { try { //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //这里用的是微软JDBC驱动 con = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;databaseName=你的数据库","数据库登入名","数据库登入密码"); Statement stmt = con.createStatement(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse("sqltoxml.xml"); NodeList n1 = doc.getElementsByTagName("ICDM001"); for(int i=0;i<n1.getLength();i++){ Element node = (Element)n1.item(i); ICDM0a00 = node.getElementsByTagName("ICDM0a00").item(0).getFirstChild().getNodeValue(); ICDM0a01 = node.getElementsByTagName("ICDM0a01").item(0).getFirstChild().getNodeValue(); ICDM0a02 = node.getElementsByTagName("ICDM0a02").item(0).getFirstChild().getNodeValue(); ICDM0a03 = node.getElementsByTagName("ICDM0a03").item(0).getFirstChild().getNodeValue(); ICDM0a04 = node.getElementsByTagName("ICDM0a04").item(0).getFirstChild().getNodeValue(); ICDM0a05 = node.getElementsByTagName("ICDM0a05").item(0).getFirstChild().getNodeValue(); ICDM0a06 = node.getElementsByTagName("ICDM0a06").item(0).getFirstChild().getNodeValue(); sql = "insert into ICDM001(ICDM0a00,ICDM0a01,ICDM0a02,ICDM0a03,ICDM0a04,ICDM0a05,ICDM0a06) values('"+ICDM0a00+"','"+ICDM0a01+"','"+ICDM0a02+"',"+ICDM0a03+","+ICDM0a04+","+ICDM0a05+","+ICDM0a06+")"; stmt.executeUpdate(sql); } stmt.close(); con.close(); }catch(Exception e){ e.printStackTrace(); } } }
<?xml version="1.0" encoding="utf-8"?> <Begin> <ICDM001> <ICDM0a00>001</ICDM0a00> <ICDM0a01>A</ICDM0a01> <ICDM0a02>PC-201011081048</ICDM0a02> <ICDM0a03>NULL</ICDM0a03> <ICDM0a04>2.0</ICDM0a04> <ICDM0a05>1</ICDM0a05> <ICDM0a06>NULL</ICDM0a06> </ICDM001> <ICDM001> <ICDM0a00>001</ICDM0a00> <ICDM0a01>B</ICDM0a01> <ICDM0a02>Tcomputer</ICDM0a02> <ICDM0a03>NULL</ICDM0a03> <ICDM0a04>2.0</ICDM0a04> <ICDM0a05>1</ICDM0a05> <ICDM0a06>NULL</ICDM0a06> </ICDM001> </Begin>