使用DOM和XSL来格式化由Java提取的数据

ZDNet软件频道 时间:2003-07-31 作者:ZDNet China,周靖 译 |  我要评论()
本文关键词:
在上一篇文章中,我们演示了如何从数据库中程序化地提取数据。现在,让我们讨论如何生成DOM对象,并用一个XSL样式表来格式化数据。
本文译自Builder.com,未经许可请勿转载Java可从任何JDBC兼容数据库提取数据,将数据转换成一个DOM对象,然后用XSL将数据格式化成需要的形式。在上一篇文章中,我们演示了如何从数据库中程序化地提取数据。现在,让我们讨论如何生成DOM对象,并用一个XSL样式表来格式化数据。这样一来,最终的输出就可用于任何应用程序,只要你为它们提供需要的输入。

生成DOM文档

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文档是在内存中创建的。


百度大联盟认证黄金会员Copyright© 1997- CNET Networks 版权所有。 ZDNet 是CNET Networks公司注册服务商标。
中华人民共和国电信与信息服务业务经营许可证编号:京ICP证010391号 京ICP备09041801号-159
京公网安备:1101082134