上节简单的讲述了一下,如何将XML数据存入DB2数据库。这节就来讲一下,如何将数据库中的XML数据读出来,并做相应转换供我们使用其中的数据。
这里根据主键取出数据库中需要的数据。这里我们先取出DB2中的数据,最初为Blob型,然后将Blob转换为输入流, 利用Dom4j读取输入流并转换成org.dom4j.Document对象。最后将org.dom4j.Document对象转换成org.w3c.dom.Document对象。请看具体代码:
package com; import java.io.InputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.dom4j.io.SAXReader; public class Dom4jToW3CDoc{ public Blob queryPlcyData(String coyNum, String plcyNum) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rsultSet = null; Blob b = null; String sql = "SELECT PLCYNUM FROM E_PLCY WHERE PLCYNUM = ? AND COYNUM = ?"; try { //conn = DButil.getPoolConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, plcyNum); pstmt.setString(2, coyNum); rsultSet = pstmt.executeQuery(); if (rsultSet.next()) { b = rsultSet.getBlob("PLCYNUM"); } }catch(Exception e){ } return b; } public static org.w3c.dom.Document toW3CDocument(Blob blob) throws Exception{ InputStream inputStream = blob.getBinaryStream(); //将Blob转换成输入流 SAXReader reader = new SAXReader(); org.dom4j.Document doc = null ; org.w3c.dom.Document w3doc = null; org.dom4j.io.DOMWriter d4Writer = new org.dom4j.io.DOMWriter(); try { doc = reader.read(inputStream) ; //将输入流转换成org.dom4j.Document doc.setXMLEncoding("GBK"); //设置编码格式 w3doc = d4Writer.write(doc); //org.dom4j.Document转换成org.w3c.dom.Document } catch (Exception e) { throw e; } return w3doc; } }
下章讲述如何利用反射机制将org.w3c.dom.Document对象中Element里的内容映射到实体类对象中