資料庫在資料查詢,修改,儲存,安全等方面與其他資料處理手段有絕對的優勢,而XML檔案是基於標記的文字檔案,相容性好,便於組織,解析和交換資料。在某些情況下我們需要講XML資料匯入到資料庫中,發揮資料庫在管理資料方面的優勢;另一方面,我們需要講資料庫中的資料匯入到XML檔案中,以便與其它系統互動資料,發揮XML檔案在資料交換上的優勢。下我介紹普通DOM和Dom4J,兩種方式實現 XML和資料庫 互轉。
Dom4j實現XML與資料庫互轉:
英語六級詞彙 xml檔案下載
資料庫Sql程式碼:
dom4j(如對dom4j不瞭解可以點選這裡)將xml資料匯入到資料庫中:XMLToDatabase.java
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.Element; public class XMLToDatabase { public static void toDatabase(){ Connection connection=null; PreparedStatement statement=null; ResultSet rs=null; connection=JDBCUtilSingle.getInitJDBCUtil().getConnection(); String sql="INSERT INTO `xmlanddb`.`dict` (`id`, `word`, `meaning`, `lx`) VALUES (NULL, ?, ?, ?);"; try { statement=connection.prepareStatement(sql); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Document document=Dom4j.load("dict.xml"); Element root=Dom4j.getRootElement(document); List words = root.elements("word"); //word節點列表 String wordStr="",meaningStr="",lxStr=""; for (Iterator i = words.iterator(); i.hasNext();) { Element word= (Element) i.next(); //單個word節點 for(Iterator k=word.elementIterator();k.hasNext();){ //遍歷 name mean lx節點 Element element = (Element) k.next(); if(element.getName().equals("name")){ wordStr=element.getText(); } if(element.getName().equals("mean")){ meaningStr=element.getText(); } if(element.getName().equals("lx")){ lxStr=element.getText(); } } try { statement.setString(1,wordStr); statement.setString(2,meaningStr); statement.setString(3,lxStr); statement.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } JDBCUtilSingle.getInitJDBCUtil().closeConnection(rs, statement, connection); } public static void main(String[] args){ toDatabase(); } }
dom4j(如對dom4j不瞭解可以點選這裡)將資料庫中記錄匯入到xml檔案中:DatabaseToXML.java
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.XMLWriter; public class DatabaseToXML { public static void toXML(){ Connection connection=null; PreparedStatement statement=null; ResultSet rs=null; connection=JDBCUtilSingle.getInitJDBCUtil().getConnection(); String sql="SELECT * FROM `dict`"; Document document = DocumentHelper.createDocument(); Element root = document.addElement("dict");// 建立根節點 try { statement=connection.prepareStatement(sql); rs=statement.executeQuery(); while(rs.next()){ Element word = root.addElement("word"); Element name = word.addElement("name"); name.setText(rs.getString("word")); Element mean=word.addElement("mean"); mean.addCDATA(rs.getString("meaning")); Element lx=word.addElement("lx"); lx.addCDATA(rs.getString("lx")); } XMLWriter writer=new XMLWriter(new FileWriter(new File("dict2.xml"))); writer.write(document); writer.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { // TODO Auto-generated method stub toXML(); } }
普通Dom(java中dom解析器不瞭解可以點選這裡)實現XML與資料庫互轉:
student2.xml
Sql程式碼:
Dom(java中dom解析器不瞭解可以點選這裡)將xml資料匯入到資料庫中:XMLToDatabaseWithDom.java
import java.io.File; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * 講XML檔案匯入到資料庫 * @author licheng * */ public class XMLToDatabaseWithDom { /** * 講 學生XML檔案匯入到資料庫中 */ public void toDatabase(){ Connection connection=null; PreparedStatement statement=null; ResultSet rs=null; connection=JDBCUtilSingle.getInitJDBCUtil().getConnection(); String sql="INSERT INTO `xmlanddb`.`student` (`number`, `name`, `date`, `height`) VALUES (?,?,?,?);"; try { statement=connection.prepareStatement(sql); DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setIgnoringElementContentWhitespace(true); //忽略空白縮排 DocumentBuilder domParser=factory.newDocumentBuilder(); Document document=domParser.parse(new File("student2.xml")); //通過已經存在的檔案建立Document物件 Element root=document.getDocumentElement(); NodeList list1=root.getElementsByTagName("學號"); NodeList list2=root.getElementsByTagName("姓名"); NodeList list3=root.getElementsByTagName("出生日期"); NodeList list4=root.getElementsByTagName("身高"); int size=list1.getLength(); //獲取長度 String[] number=new String[4]; String[] name=new String[4]; String[] date=new String[4]; double[] height=new double[4]; for(int k=0;k<size;k++){ Node numberNode=list1.item(k); Node nameNode=list2.item(k); Node dateNode=list3.item(k); Node heightNode=list4.item(k); number[k]=numberNode.getTextContent().trim(); name[k]=nameNode.getTextContent().trim(); date[k]=dateNode.getTextContent().trim(); height[k]=Double.parseDouble(heightNode.getTextContent().trim()); statement.setString(1, number[k]); statement.setString(2, name[k]); statement.setString(3, date[k]); statement.setDouble(4, height[k]); statement.executeUpdate(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ JDBCUtilSingle.getInitJDBCUtil().closeConnection(rs, statement, connection); } } /** * 讀取資料庫中的資料 */ public void getItemFromDatabase(){ Connection connection=null; PreparedStatement statement=null; ResultSet rs=null; connection=JDBCUtilSingle.getInitJDBCUtil().getConnection(); String sql="SELECT * FROM `student` "; try { statement=connection.prepareStatement(sql); rs=statement.executeQuery(); while(rs.next()){ System.out.println(rs.getString(1)+rs.getString(2)+rs.getString(3)+rs.getDouble(4)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args){ //new XMLToDatabase().toDatabase(); new XMLToDatabaseWithDom().getItemFromDatabase(); } }
Dom(java中dom解析器不瞭解可以點選這裡)將資料庫中記錄匯入到xml檔案中:DatabaseToXMLWithDom.java
import java.io.File; import java.io.FileOutputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; 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; import org.w3c.dom.Node; public class DatabaseToXMLWithDom { public void toXML(){ /** * 講資料記錄存入到陣列中 */ String[] number={""}; String[] name={""}; String[] date={""}; String[] height={""}; Connection connection=null; PreparedStatement statement=null; ResultSet rs=null; connection=JDBCUtilSingle.getInitJDBCUtil().getConnection(); String sql="SELECT * FROM `student` "; try { statement=connection.prepareStatement(sql); rs=statement.executeQuery(); rs.last(); //講遊標移到結果集的最後一行 int recordAmount=rs.getRow(); //獲取記錄資料 number=new String[recordAmount]; name=new String[recordAmount]; date=new String[recordAmount]; height=new String[recordAmount]; int k=0; rs.beforeFirst(); //講遊標移到第一條記錄前 while(rs.next()){ number[k]=rs.getString(1); name[k]=rs.getString(2); date[k]=rs.getString(3); height[k]=String.valueOf(rs.getDouble(4)); k++; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ JDBCUtilSingle.getInitJDBCUtil().closeConnection(rs, statement, connection); } /** * 將資料匯入到XML檔案 */ DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setIgnoringElementContentWhitespace(true); //忽略空白縮排 DocumentBuilder domParser; try { domParser = factory.newDocumentBuilder(); Document document=domParser.newDocument(); //通過呼叫newDocument() 方法獲取例項 document.setXmlVersion("1.0"); //設定 xml版本號 Element root=document.createElement("學生資訊"); document.appendChild(root); for(int k=0;k<name.length;k++){ Node student=document.createElement("學生"); root.appendChild(student); Node xuehao=document.createElement("學號"); xuehao.appendChild(document.createTextNode(number[k])); Node xingming=document.createElement("姓名"); xingming.appendChild(document.createTextNode(name[k])); Node chusheng=document.createElement("出生日期"); chusheng.appendChild(document.createTextNode(date[k])); Node shenggao=document.createElement("身高"); shenggao.appendChild(document.createTextNode(height[k])); student.appendChild(xuehao); student.appendChild(xingming); student.appendChild(chusheng); student.appendChild(shenggao); TransformerFactory transFactory=TransformerFactory.newInstance(); //工廠物件獲取transFactory例項 Transformer transformer=transFactory.newTransformer(); //獲取Transformer例項 DOMSource domSource=new DOMSource(document); File file=new File("newXML2.xml"); FileOutputStream out=new FileOutputStream(file); StreamResult xmlResult=new StreamResult(out); transformer.transform(domSource, xmlResult); out.close(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new DatabaseToXMLWithDom().toXML(); } }
相關內容,請檢視:
JAVA與DOM解析器基礎 學習筆記
JAVA與DOM解析器提高(DOM/SAX/JDOM/DOM4j/XPath) 學習筆記二
作者:Li-Cheng
本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連線,否則保留追究法律責任的權利。