Java的最新版本支持JAXP XML处理,并实现了由万维网协会(W3C)定义的DOM API。使用这些相容于JAXP的版本,只需3行代码即可创建一个DOM文档对象,其中用到了JAXP
factory和builder方法:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
我们创建一个名为resultset的根元素,并把它添加到文档对象中
Element root = document.createElement("resultset");
document.appendChild(root);
resultset游标遍历结果集时,在根元素中添加包含行数据的一个新元素:
Element nextRow = document.createElement("row");
列计数必须从ResultSetMetaData对象中读取;在本项目的数据库数据提取阶段,它必须是已经定义好的:
int columnCount = rsmd.getColumnCount();
列名要用for循环来检索;针对每个列名,都添加一个name节点,它带有一个子TextNode,其中包含用于一个names元素的名值:
String[] columnNames = new String[columnCount];
Element names = document.createElement("names");
for (int i = 0; i < columnCount; i++){
/* the first column is 1, the second is 2, ... */
columnNames[i] = rsmd.getColumnName(i + 1);
Element nextNameNode = document.createElement("name");
Text nextName = document.createTextNode(columnNames[i]);
nextNameNode.appendChild(nextName);
names.appendChild(nextNameNode);
}
列索引从1开始,而非从0开始。读取每个数据行时,列值都在一个for循环中作为字符串来泛化地检索,这个for循环将读取每一个列值:
/* Move the cursor through the data one row at
a time. */
while(resultSet.next()){
/* Create an Element node for each row of data. */
Element nextRow = document.createElement("row");
if (debug) System.out.println("new row");
for (int i = 0; i < columnCount; i++){
/* Create an Element node for each column value. */
Element nextNode = document.createElement(columnNames[i]);
/* the first column is 1, the second is 2, ... */
/* getString() will retrieve any of the basic SQL types*/
Text text = document.createTextNode(resultSet.getString(i + 1));
nextNode.appendChild(text);
nextRow.appendChild(nextNode);
}
root.appendChild(nextRow);
}
所有数据都转换到一个DOM文档对象中之后,连接就可关闭。DataBaseHandler永远不需要进行文件操作。XML文档是在内存中创建的。