XMLBeans入門

一、關於XML解析
  XML在Java應用程序裏變得越來越重要, 廣泛應用於數據存儲和交換. 比如我們常見的配置文件,都是以XML方式存儲的. XML還應用於Java Message Service和Web Services等技術作爲數據交換.因此,正確讀寫XML文檔是XML應用的基礎.
  Java提供了SAX和DOM兩種方式用於解析XML,但即便如此,要讀寫一個稍微複雜的XML,也不是一件容易的事.
二、XMLBean簡介
   Hibernate已經成爲目前流行的面向Java環境的對象/關係數據庫映射工具.在Hibernate等對象/關係數據庫映射工具出現之前,對數據 庫的操作是通過JDBC來實現的,對數據庫的任何操作,開發人員都要自己寫SQL語句來實現. 對象/關係數據庫映射工具出現後,對數據庫的操作轉成對JavaBean的操作,極大方便了數據庫開發. 所以如果有一個類似的工具能夠實現將對XML的讀寫轉成對JavaBean的操作,將會簡化XML的讀寫,即使對XML不熟悉的開發人員也能方便地讀寫 XML. 這個工具就是XMLBean.
三、準備XMLBean和XML文檔
  XMLBean是Apache的一個開源項目,可以從http://www.apache.org下載,最新的版本是2.0. 解壓後目錄如下:
xmlbean2.0.0   
 +---bin   
 +---docs   
 +---lib  
 +---samples   
 +---schemas
bin 目錄裏是一些命令,我們就是使用這些命令來生成xmlbean
爲了演示一個例子,準備一個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>

這 是一個客戶的數據模型,每個客戶都有客戶編號(ID),姓名,性別(gender),電話號碼(phoneNumber)和地址,其中地址有兩個: 首要地址(PrimaryAddress)和帳單地址(BillingAddress),每個地址有郵編,地址1,和地址2組成.其中帳單地址還有收件人 (receiver).

四、XMLBean使用步驟
  和其他面向Java環境的對象/關係數據庫映射工具的使用步驟一樣,在正式使用XMLBean前,我們要作兩個準備.
  1. 生成XML Schema文件
  什麼是XML Schema文件?
    正常情況下,每個XML文件都有一個Schema文件,XML Schema文件是一個XML的約束文件,它定義了XML文件的結構和元素.以及對元素和結構的約束. 通俗地講,如果說XML文件是數據庫裏的記錄,那麼Schema就是表結構定義.
  爲什麼需要這個文件?
   XMLBean需要通過這個文件知道一個XML文件的結構以及約束,比如數據類型等. 利用這個Schema文件,XMLBean將會產生一系列相關的Java Classes來實現對XML的操作. 而作爲開發人員,則是利用XMLBean產生的Java Classes來完成對XML的操作而不需要SAX或DOM.
   怎樣產生這個Schema文件呢?
    如果對於熟悉XML的開發人員,可以自己來寫這個Schema文件,對於不熟悉XML的開發人員,可以通過一些工具來完成.比較有名的如XMLSPY和 Stylus Studio都可以通過XML文件來生成Schema文件. 加入我們已經生成這個Schema文件(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的目錄下. 通過這個工具,我們可以將以上的Schema文件生成Java Classes.scomp的語法如下:-
  scomp [options] [dirs]* [schemaFile.xsd]* [service.wsdl]* [config.xsdconfig]*
  主要參數說明:
  -src [dir] -- 生成的Java Classes存放目錄
  -srconly -- 不編譯Java Classes,不產生Jar文件
  -out [jarFileName] -- 生成的Jar文件,缺省是xmltypes.jar
  -compiler -- Java編譯器的路徑,即Javac的位置
  schemaFile.xsd -- XML Schema文件位置
    config.xsdconfig -- xsdconfig文件的位置, 這個文件主要用來制定生成的Java Class的一些文件名規則和Package的名稱,在本文,package是sample.xmlbean
準備一個配置文件(文件名customer.xsdconfig),它的內容如下:
<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>
    
  在本文,我是這樣運行的:
      scomp -src src  -out customerXmlBean.jar customer.xsd    -compiler "C:/Program Files/Java/jdk1.6.0/bin/javac" customer.xsdconfig
  這個命令行 的意思是告訴scomp生成customerXmlBean.jar,放在build目錄下,同時生成源代碼放在build/src下, Schema文件是customer.xsd,xsdconfig文件是customer.xsdconfig.其實, 生成的Java源代碼沒有多大作用,我們要的是jar文件.我們先看一下src/sample/xmlbean下生成的Classes.
  CustomersDocument.java -- 整個XML文檔的Java Class映射
  CustomerType.java -- 節點sustomer的映射
  AddressType.java -- 節點address的映射
  BillingAddressType.java -- 節點billingAddress的映射
  PrimaryAddressType.java -- 節點primaryAddress的映射
    好了,到此我們所有的準備工作已經完成了. 下面就開始進入重點:利用剛纔生成的jar文件讀寫XML.
   
五、利用XMLBean讀XML文件
  新建一個Java Project,將XMLBean2.0.0/lib/下的Jar文件和剛纔我們生成的customerXmlBean.jar加入到Project的ClassPath.
  新建一個Java Class: 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());
                // 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();
    }
}
運行它,參看輸出結果:
 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

  怎麼樣,是不是很輕鬆? XMLBean的威力.
六、利用XMLBean寫XML文件
  利用XMLBean創建一個XML文檔也是一件輕而易舉的事.我們再增加一個Method,
  請看一下的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();
    }
  運行,打開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文件
  我們再增加一個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");
   }
  運行之後,我們將會看到客戶編號爲3的客戶的lastname已經改爲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();
        }
    }
  運行,我們將會看到客戶編號爲3的客戶的資料已經被刪除.
九、*.xsdconfig 更多用法
這裏只是簡單介紹一個用法,其他用法,可以參考 xmlbeans 目錄裏 Sample/xsdconfig 目錄裏的例子。
在應用中,我們可能會解析許多種xml文件,但是我們的系統中又不想引入太多額外的jar文件,因此,一個xml文件生成一個jar文件就顯得不好了,好的方式是所有的xml class 都放到一個jar裏,並且組織在各自的包裏。
針對這種需求,我們來做一個例子:
首先寫 .xsd 文件.如果不熟悉,xsd 文件建議使用工具生成(比如xmlspy),當然前提得了解一下xsd的基本知識。比如說下面的 xsd 文件
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--W3C Schema 由 XMLSpy v2006 U 創建 (http://www.altova.com)-->
<xs:schema
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:ct="http://xxx"
    targetNamespace="http://xxx"
    elementFormDefault="qualified">
    <xs:element name="TestTable">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="ct:packagename"/>
                <xs:element ref="ct:voname"/>
                <xs:element ref="ct:tablename"/>
                <xs:element ref="ct:db" maxOccurs="unbounded"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element name="db">
        <xs:complexType>
            <xs:attribute name="column" type="xs:string" use="required"/>
            <xs:attribute name="jdbcType" type="xs:string" use="required"/>
            <xs:attribute name="primary" type="xs:string" use="required"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="packagename" type="xs:string"/>
    <xs:element name="tablename" type="xs:string"/>
    <xs:element name="voname" type="xs:string"/>
</xs:schema>   

    xmlns:ct="http://xxx"
    targetNamespace="http://xxx"    這個是我們給這個 xsd 文件起的命名空間的名字。
        注意這個(紅色部分):<xs:element ref="ct:packagename"/>    如果你定義了命名空間,那麼如果要使用 ref ,就必須加上命名空間的名字,否則使用scomp的    命令的時候,會提示找不到 element.
下面我們修改一下 xsdconfig 文件
<xb:config xmlns:xb="http://xml.apache.org/xmlbeans/2004/02/xbean/config"
    xmlns:ct="http://xxx" xmlns:test2="http://test2">

  <xb:namespace uri="http://xxx">
    <xb:package>sample.testxmlbean</xb:package>
  </xb:namespace>
   
    <xb:namespace uri="http://test2">
    <xb:package>sample.xmlbean</xb:package>
  </xb:namespace>
   
</xb:config>   
   
    爲了    舉例子說明在 xsdconfig 文件裏可以使用很多個命名空間,這裏加了其他一個命名空間作爲例子,也就是藍色字部分。通過這樣修改 xsdconfig 文件,我們就可以爲不同的xsd文件,生成不同的包的結構。
    一個 uri 也可以包含很多個命名空間,比如:
    <xb:namespace uri="http://xxx  http://yyy  http://zzz">

使用 scomp 命令scomp –src build/src –out build/test.jar test.xsd test2.xsd test.xsdconfigscomp 命令可以加很多個 xsd 文件作爲參數。
十、下載資源
XmlSpy : http://cc163.driversky.com/down/AltovaXMLSpy2006.rar
XmlBeans: http://mirror.vmmatrix.net/apache/xmlbeans/
          http://mirror.vmmatrix.net/apache/xmlbeans/xmlbeans-current.zip
  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章