内容摘要:通过使用 XML 数据模型,就可以取消整个数据对象包装器层次结构,让开发人员将注意力集中在业务逻辑上,而不会为业务数据管理分心。通过使用 DOM 包装器类,应用程序代码可以与 DOM API 隔离开。
第一种情况 —— 数据在数据库中存储为 XML 格式
清单 6. 重写应用程序来使用 XML 模型
1. Statement dbstmt= conn.createStatement();
2. ResultSet dbResult = dbstmt.executeQuery("select custXML from
customer_table where customerid=custid");
3. XMLParse customerXML = new XMLParse(dbResult. getString(1));
4. customerXML.appendNode("/Customer", customerXML.createNode ("<Items/>"))
5. dbResult = dbstmt.executeQuery("select itemXML from purchase_table
where customerid=custid");
6. While (dbResult.rs.next ()) {
7. Node itemnode= customerXML.createNode (dbResult. getString(1));
8. customerXML.appendNode(itemnode ,"/Customer/Items",false);
}
9. customerXML.find("/Customer/Items/item[@price>15.0 and @price <25.5]",true);
10. for(int i=0;i < customerXML.currentFind.getLength();i++) {
11. System.out.println(customerXML.getValue("@description",i));
}
第一个查询(第 2 行)返回给定客户的 custXML 列中的 XML 数据。将这个 XML 字符串传递给 DOM 包装器的构造器(第 3 行),DOM 包装器进而使用 XML 解析器实例化一个代表 XML 数据的对象层次结构。
注意:因为客户 XML 中还没有任何 Items 元素(这符合我们在模型中定义的 XML 模式),所以我们创建一个新的 Items 元素(第 4 行),并把它作为子元素追加到 Customer 元素中。
第二个查询(第 5 行)从数据库中获取这位客户购买的商品的列表。将列表中的每个商品(第 7 行)追加到 DOM 对象层次结构中 Customer/items 路径的下面(第 8 行)。
责编:豆豆技术应用