??xml version="1.0" encoding="utf-8" standalone="yes"?>
原文:[http://www.matrix.org.cn/resource/article/44/44027_XMLBean.html]http://www.matrix.org.cn/resource/article/44/44027_XMLBean.html[/url]
关键?XML XMLBean Parser
一、关于XML解析
XML在Java应用E序里变得越来越重要, q泛应用于数据存储和
交换. 比如我们常见的配|文?都是以XML方式存储? XMLq应?BR>于Java Message Service和W(xu)eb Services{技术作为数据交?
因此,正确dXML文档是XML应用的基.
Java提供?jin)SAX和DOM两种方式用于解析XML,但即便如?要读写一?BR>E微复杂的XML,也不是一件容易的?
二、XMLBean?/SPAN>
Hibernate已经成ؓ(f)目前行的面向Java环境的对?关系数据库映工?
在Hibernate{对?关系数据库映工具出C?Ҏ(gu)据库的操作是
通过JDBC来实现的,Ҏ(gu)据库的Q何操?开发h员都要自己写SQL语句
来实? 对象/关系数据库映工具出现后,Ҏ(gu)据库的操作{成对
JavaBean的操?极大方便?jin)数据库开? 所以如果有一个类似的工具能够
实现对XML的读写{成对JavaBean的操?会(x)化XML的读?即对XML
不熟(zhn)的开发h员也能方便地dXML. q个工具是XMLBean.
三、准备XMLBean和XML文档
XMLBean是Apache的一个开源项?可以从http://www.apache.org下蝲,
最新的版本?.0. 解压后目录如?
xmlbean2.0.0
+---bin
+---docs
+---lib
+---samples
+---schemas
另外q要准备一个XML文档(customers.xml),
在本文的例子?我们对q个文档q行d操作. 文档源码如下:
<?xml version="1.0" encoding="UTF-8"?>
<Customers>
<customer>
<id>1</id>
<gender>female</gender>
<firstname>Jessica</firstname>
<lastname>Lim</lastname>
<phoneNumber>1234567</phoneNumber>
<address>
<primaryAddress>
<postalCode>350106</postalCode>
<addressLine1>#25-1</addressLine1>
<addressLine2>SHINSAYAMA 2-CHOME</addressLine2>
</primaryAddress>
<billingAddress>
<receiver>Ms Danielle</receiver>
<postalCode>350107</postalCode>
<addressLine1>#167</addressLine1>
<addressLine2>NORTH TOWER HARBOUR CITY</addressLine2>
</billingAddress>
</address>
</customer>
<customer>
<id>2</id>
<gender>male</gender>
<firstname>David</firstname>
<lastname>Bill</lastname>
<phoneNumber>808182</phoneNumber>
<address>
<primaryAddress>
<postalCode>319087</postalCode>
<addressLine1>1033 WS St.</addressLine1>
<addressLine2>Tima Road</addressLine2>
</primaryAddress>
<billingAddress>
<receiver>Mr William</receiver>
<postalCode>672993</postalCode>
<addressLine1>1033 WS St.</addressLine1>
<addressLine2>Tima Road</addressLine2>
</billingAddress>
</address>
</customer>
</Customers>
q是一个客L(fng)数据模型,每个客户都有客户~号(ID),姓名,性别(gender),
?sh)话L(fng)(phoneNumber)和地址,其中地址有两? 首要地址(PrimaryAddress)
和帐单地址(BillingAddress),每个地址有邮~?地址1,和地址2l成.
其中帐单地址q有收g?receiver).
此外,q要准备一个配|文?文g名customer.xsdconfig),q个文g?BR>作用我后面会(x)?它的内容如下:
<xb:config xmlns:xb="http://xml.apache.org/xmlbeans/2004/02/xbean/config">
<xb:namespace>
<xb:package>sample.xmlbean</xb:package>
</xb:namespace>
</xb:config>
四、XMLBean使用步骤
和其他面向Java环境的对?关系数据库映工L(fng)使用步骤一?
在正式用XMLBean?我们要作两个准备.
1. 生成XML Schema文g
什么是XML Schema文g? 正常情况?每个XML文g都有一个Schema文g,
XML Schema文g是一个XML的约束文?它定义了(jin)XML文g的结构和元素.
以及(qing)对元素和l构的约? 通俗地讲,如果说XML文g是数据库里的记录,
那么Schema是表结构定?
Z么需要这个文? XMLBean需要通过q个文g知道一个XML文g?BR> l构以及(qing)U束,比如数据cd{? 利用q个Schema文g,XMLBean会(x)产生
一pd相关的Java Classes来实现对XML的操? 而作为开发h?则是
利用XMLBean产生的Java Classes来完成对XML的操作而不需要SAX或DOM.
怎样产生q个Schema文g? 如果对于熟?zhn)XML的开发h?可以自己?BR> 写这个Schema文g,对于不熟(zhn)XML的开发h?可以通过一些工h完成.
比较有名的如XMLSPY和Stylus Studio都可以通过XML文g来生成Schema
文g. 加入我们已经生成q个Schema文g(customer.xsd):
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:element name="Customers">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="customer"
type="customerType"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="customerType">
<xs:sequence>
<xs:element name="id" type="xs:int"/>
<xs:element name="gender" type="xs:string"/>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="phoneNumber" type="xs:string"/>
<xs:element name="address" type="addressType"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="addressType">
<xs:sequence>
<xs:element name="primaryAddress" type="primaryAddressType"/>
<xs:element name="billingAddress" type="billingAddressType"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="primaryAddressType">
<xs:sequence>
<xs:element name="postalCode" type="xs:string"/>
<xs:element name="addressLine1" type="xs:string"/>
<xs:element name="addressLine2" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="billingAddressType">
<xs:sequence>
<xs:element name="receiver" type="xs:string"/>
<xs:element name="postalCode" type="xs:string"/>
<xs:element name="addressLine1" type="xs:string"/>
<xs:element name="addressLine2" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
2. 利用scomp来生成Java Classes
scomp是XMLBean提供的一个编译工?它在bin的目录下. 通过q个工具,
我们可以以上的Schema文g生成Java Classes.
scomp的语法如?-
scomp [options] [dirs]* [schemaFile.xsd]* [service.wsdl]* [config.xsdconfig]*
主要参数说明:
-src [dir] -- 生成的Java Classes存放目录
-srconly -- 不编译Java Classes,不生Jar文g
-out [jarFileName] -- 生成的Jar文g,~省是xmltypes.jar
-compiler -- Java~译器的路径,即Javac的位|?BR> schemaFile.xsd -- XML Schema文g位置
config.xsdconfig -- xsdconfig文g的位|? q个文g主要用来制定生成的Java Class
的一些文件名规则和Package的名U?在本?package是sample.xmlbean
在本?我是q样q行?
scomp -src build\src -out build\customerXmlBean.jar schema\customer.xsd
-compiler C:\jdk142_04\bin\javac customer.xsdconfig
q个命o(h)行的意思是告诉scomp生成customerXmlBean.jar,攑֜build目录?同时
生成源代码放在build\src? Schema文g是customer.xsd,xsdconfig文g是customer.xsdconfig.
其实, 生成的Java源代码没有多大作?我们要的是jar文g.我们先看一下build\src\sample\xmlbean下生成的Classes.
CustomersDocument.java -- 整个XML文档的Java Class映射
CustomerType.java -- 节点sustomer的映?BR> AddressType.java -- 节点address的映?BR> BillingAddressType.java -- 节点billingAddress的映?BR> PrimaryAddressType.java -- 节点primaryAddress的映?BR>
好了(jin),到此我们所有的准备工作已经完成? 下面开始进入重点:(x)利用刚才生成的jar文gdXML.
五、利用XMLBean读XML文g
新徏一个Java Project,XMLBean2.0.0\lib\下的Jar文g和刚才我们生成的customerXmlBean.jar加入
到Project的ClassPath.
新徏一个Java Class: CustomerXMLBean. 源码如下:
package com.sample.reader;
import java.io.File;
import sample.xmlbean.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.xmlbeans.XmlOptions;
public class CustomerXMLBean {
private String filename = null;
public CustomerXMLBean(String filename) {
super();
this.filename = filename;
}
public void customerReader() {
try {
File xmlFile = new File(filename);
CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile);
CustomerType[] customers = doc.getCustomers().getCustomerArray();
for (int i = 0; i < customers.length; i++) {
CustomerType customer = customers[i];
println("Customer#" + i);
println("Customer ID:" + customer.getId());
println("First name:" + customer.getFirstname());
println("Last name:" + customer.getLastname());
println("Gender:" + customer.getGender());
println("PhoneNumber:" + customer.getPhoneNumber());
// Primary address
PrimaryAddressType primaryAddress = customer.getAddress().getPrimaryAddress();
println("PrimaryAddress:");
println("PostalCode:" + primaryAddress.getPostalCode());
println("AddressLine1:" + primaryAddress.getAddressLine1());
println("AddressLine2:" + primaryAddress.getAddressLine2());
// Billing address
BillingAddressType billingAddress = customer.getAddress().getBillingAddress();
println("BillingAddress:");
println("Receiver:" + billingAddress.getReceiver());
println("PostalCode:" + billingAddress.getPostalCode());
println("AddressLine1:" + billingAddress.getAddressLine1());
println("AddressLine2:" + billingAddress.getAddressLine2());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void println(String str) {
System.out.println(str);
}
public static void main(String[] args) {
String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers.xml";
CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
customerXMLBean.customerReader();
}
}
q行?参看输出l果:
Customer#0
Customer ID:1
First name:Jessica
Last name:Lim
Gender:female
PhoneNumber:1234567
PrimaryAddress:
PostalCode:350106
AddressLine1:#25-1
AddressLine2:SHINSAYAMA 2-CHOME
BillingAddress:
Receiver:Ms Danielle
PostalCode:350107
AddressLine1:#167
AddressLine2:NORTH TOWER HARBOUR CITY
Customer#1
Customer ID:2
First name:David
Last name:Bill
Gender:male
PhoneNumber:808182
PrimaryAddress:
PostalCode:319087
AddressLine1:1033 WS St.
AddressLine2:Tima Road
BillingAddress:
Receiver:Mr William
PostalCode:672993
AddressLine1:1033 WS St.
AddressLine2:Tima Road
怎么?是不是很L? XMLBean的威?
六、利用XMLBean写XML文g
利用XMLBean创徏一个XML文档也是一件轻而易丄?我们再增加一个Method,
L(fng)一下的Java Class:
public void createCustomer() {
try {
// Create Document
CustomersDocument doc = CustomersDocument.Factory.newInstance();
// Add new customer
CustomerType customer = doc.addNewCustomers().addNewCustomer();
// set customer info
customer.setId(3);
customer.setFirstname("Jessica");
customer.setLastname("Lim");
customer.setGender("female");
customer.setPhoneNumber("1234567");
// Add new address
AddressType address = customer.addNewAddress();
// Add new PrimaryAddress
PrimaryAddressType primaryAddress = address.addNewPrimaryAddress();
primaryAddress.setPostalCode("350106");
primaryAddress.setAddressLine1("#25-1");
primaryAddress.setAddressLine2("SHINSAYAMA 2-CHOME");
// Add new BillingAddress
BillingAddressType billingAddress = address.addNewBillingAddress();
billingAddress.setReceiver("Ms Danielle");
billingAddress.setPostalCode("350107");
billingAddress.setAddressLine1("#167");
billingAddress.setAddressLine2("NORTH TOWER HARBOUR CITY");
File xmlFile = new File(filename);
doc.save(xmlFile);
} catch (Exception ex) {
ex.printStackTrace();
}
}
修改main method.
public static void main(String[] args) {
String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
customerXMLBean.createCustomer();
}
q行,打开customers_new.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Customers>
<customer>
<id>3</id>
<gender>female</gender>
<firstname>Jessica</firstname>
<lastname>Lim</lastname>
<phoneNumber>1234567</phoneNumber>
<address>
<primaryAddress>
<postalCode>350106</postalCode>
<addressLine1>#25-1</addressLine1>
<addressLine2>SHINSAYAMA 2-CHOME</addressLine2>
</primaryAddress>
<billingAddress>
<receiver>Ms Danielle</receiver>
<postalCode>350107</postalCode>
<addressLine1>#167</addressLine1>
<addressLine2>NORTH TOWER HARBOUR CITY</addressLine2>
</billingAddress>
</address>
</customer>
</Customers>
七、利用XMLBean修改XML文g
我们再增加一个Method:
public void updateCustomer(int id,String lastname) {
try {
File xmlFile = new File(filename);
CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile);
CustomerType[] customers = doc.getCustomers().getCustomerArray();
for (int i = 0; i < customers.length; i++) {
CustomerType customer = customers[i];
if(customer.getId()==id){
customer.setLastname(lastname);
break;
}
}
doc.save(xmlFile);
} catch (Exception ex) {
ex.printStackTrace();
}
}
main method:
public static void main(String[] args) {
String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
customerXMLBean.updateCustomer(3,"last");
}
q行之后,我们会(x)看到客户~号?的客L(fng)lastname已经改ؓ(f)last.
八、利用XMLBean删除一个customer
再增加一个Method:
public void deleteCustomer(int id) {
try {
File xmlFile = new File(filename);
CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile);
CustomerType[] customers = doc.getCustomers().getCustomerArray();
for (int i = 0; i < customers.length; i++) {
CustomerType customer = customers[i];
if(customer.getId()==id){
customer.setNil() ;
break;
}
}
doc.save(xmlFile);
} catch (Exception ex) {
ex.printStackTrace();
}
}
main method:
public static void main(String[] args) {
String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
customerXMLBean.deleteCustomer(3);
}
q行,我们会(x)看到客户~号?的客L(fng)资料已经被删?
?ji)、查询XML
除了(jin)本文在以上讲q的,利用XMLBean能轻L村֮成XML的读写操作外,l合XPath和XQuery,
XMLBeanq能完成象SQL查询数据库一h便地查询XML数据. 关于XML查询以及(qing)如何创徏XML数据? 我将在另一文章里讨论.
十、结束语
XMLBean能帮助我们轻易读写XML,q将有助于我们降低XML的学?fn)和使?有了(jin)q个基础,
开发h员将为学?fn)更多地XML相关技术和W(xu)eb Services,JMS{其他J2EE技术打下良好地基础.
]]>
]]>