在 Java 應用裡,XML 的分量一年比一年重。從最常見的專案設定檔,到 Java Message Service、Web Services 這類跨系統整合方案,XML 幾乎成了資料交換的通用語言。可以說,能不能把 XML 讀得進、寫得出,直接決定了後面所有應用的成敗。
問題在於,Java 平台雖然提供了 SAX 與 DOM 兩套解析機制,可真要拿它們去處理一份結構稍微複雜一點的 XML,程式碼就會迅速膨脹成一團難以維護的樣板。節點遍歷、型別轉換、空值判斷,樣樣都得自己動手。
先回想一下資料庫這條路是怎麼走過來的。在 Hibernate 這類物件/關聯對應工具普及之前,操作資料庫全靠 JDBC,每一句 SQL 都得自己敲。對應工具出現之後,開發者面對的不再是資料表與游標,而是乾乾淨淨的 JavaBean,資料庫開發的門檻一下子降了下來。
XMLBean 走的正是同一條思路:把「讀 XML、寫 XML」這件事,轉化成「操作 JavaBean」。它就是 Apache 基金會的開源專案,目的很明確——讓連 XML 都不熟的開發者,也能用 setter/getter 這種最直覺的方式把 XML 玩轉起來。
XMLBean 可以從 Apache 官方網站取得,本文以 2.0 版為例。解壓後的目錄大致如下:
xmlbean2.0.0
+---bin
+---docs
+---lib
+---samples
+---schemas
接著準備一份待操作的 XML 檔 customers.xml,本文所有示範都圍繞它展開:
<?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>
這是一份典型的客戶資料模型:每位客戶有編號、姓名、性別、電話,以及兩種地址——通訊用的 primaryAddress 與寄帳單用的 billingAddress。每個地址由郵遞區號與兩行地址組成,帳單地址多一個收件人欄位。
另外還要準備一個名為 customer.xsdconfig 的設定檔,用途稍後說明:
<xb:config xmlns:xb="https://xml.apache.org/xmlbeans/2004/02/xbean/config">
<xb:namespace>
<xb:package>sample.XMLbean</xb:package>
</xb:namespace>
</xb:config>
每一份 XML 文件背後,通常都對應著一份 Schema。Schema 約束了文件的結構、元素名稱與資料型別——如果說 XML 檔是資料庫裡的一筆筆記錄,那 Schema 就是表結構定義。
XMLBean 正是靠 Schema 來理解一份 XML 的長相,進而產生一整套對應的 Java 類別;開發者只要操作這些類別,再也用不着直接跟 SAX 或 DOM 纏鬥。
Schema 可以自己寫,也可以交給工具生成。XMLSpy、Stylus Studio 這類編輯器都能由 XML 檔反向導出 Schema。假設我們已經有了 customer.xsd:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="https://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>
scomp 是 XMLBean 附帶的編譯工具,位於 bin 目錄。語法如下:
scomp [options] [dirs]* [schemaFile.xsd]* [service.wsdl]* [config.xsdconfig]*
常用參數:
- -src [dir]:指定產生的 Java 原始碼存放位置
- -srconly:只產生原始碼,不編譯、不打包
- -out [jarFileName]:指定輸出的 Jar 檔名,預設為 XMLtypes.jar
- -compiler:javac 的路徑
- schemaFile.xsd:Schema 檔位置
- config.xsdconfig:xsdconfig 檔位置,用來決定產生物件的命名規則與 package 名稱
本文這樣執行:
scomp -src build\src -out build\customerXMLBean.jar schema\customer.xsd
-compiler C:\jdk142_04\bin\javac customer.xsdconfig
這行指令的意思是:以 customer.xsd 為輸入,在 build 目錄下產生 customerXMLBean.jar,原始碼則放到 build\src,並套用 customer.xsdconfig 裡定義的命名規則。真正要用的其實只有那個 Jar,原始碼拿來參考即可。
跑完之後,build\src\sample\XMLbean 下會出現這幾支類別:
CustomersDocument.java——整份 XML 文件的對應類別
CustomerType.java——customer 節點
AddressType.java——address 節點
BillingAddressType.java——billingAddress 節點
PrimaryAddressType.java——primaryAddress 節點
準備工作到此結束,接下來才是重頭戲。
新建一個 Java 專案,把 xmlbean2.0.0\lib 底下的 Jar 以及剛才產生的 customerXMLBean.jar 一併加入 ClassPath,然後建立 CustomerXMLBean 類別:
package com.sample.reader;
import java.io.File;
import sample.XMLbean.*;
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());
// 通訊地址
PrimaryAddressType primaryAddress = customer.getAddress().getPrimaryAddress();
println("PrimaryAddress:");
println("PostalCode:" + primaryAddress.getPostalCode());
println("AddressLine1:" + primaryAddress.getAddressLine1());
println("AddressLine2:" + primaryAddress.getAddressLine2());
// 帳單地址
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();
}
}
執行結果:
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
整段程式裡沒有任何一行程式碼在處理標籤、屬性或命名空間,全是鏈式呼叫的 getter。這就是 XMLBean 的價值所在。
從零組出一份 XML 同樣輕鬆,只要再補一個方法:
public void createCustomer() {
try {
// 建立文件
CustomersDocument doc = CustomersDocument.Factory.newInstance();
// 新增一位客戶
CustomerType customer = doc.addNewCustomers().addNewCustomer();
customer.setId(3);
customer.setFirstname("Jessica");
customer.setLastname("Lim");
customer.setGender("female");
customer.setPhoneNumber("1234567");
// 新增地址
AddressType address = customer.addNewAddress();
PrimaryAddressType primaryAddress = address.addNewPrimaryAddress();
primaryAddress.setPostalCode("350106");
primaryAddress.setAddressLine1("#25-1");
primaryAddress.setAddressLine2("SHINSAYAMA 2-CHOME");
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:
public static void main(String[] args) {
String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
customerXMLBean.createCustomer();
}
執行完打開 customers_new.xml,會看到文件已按 Schema 定義的結構與順序生成:
<?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>
修改的做法是「先讀進來、找到目標、改欄位、再存回去」:
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();
}
}
呼叫方式:
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");
}
跑完之後,編號 3 那位客戶的 lastname 就變成了 last。
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();
}
}
呼叫方式:
public static void main(String[] args) {
String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
customerXMLBean.deleteCustomer(3);
}
執行後,編號 3 的客戶資料即被清空。
除了上面這套增刪改讀,XMLBean 搭配 XPath 與 XQuery,還能做到近乎「用 SQL 查資料庫」那樣的查詢體驗。關於 XML 查詢與 XML 資料庫的建置,值得另外用一篇文章細談。
XMLBean 把 XML 的讀寫難度壓到很低,這對整個學習曲線的意義不小:省下了跟解析器搏鬥的力氣,開發者就能把注意力放到 Web Services、JMS 這些更上層的技術上。作為進入 XML 世界的第一塊踏板,它相當稱職。
本文作者:葉楓 原文發表於 Matrix 資源站,TechTarget 經授權轉載。