首頁 後端開發 XML/RSS教程 利用XMLBean輕輕鬆鬆讀寫XML

利用XMLBean輕輕鬆鬆讀寫XML

Mar 01, 2017 pm 05:05 PM
xml

一、關於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
登入後複製

另外還要準備一個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).此外,還要準備一個設定檔(檔名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>
登入後複製

四、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

  在本文,我是這樣運行的:

 scomp -src build\src  -out build\customerXmlBean.jar schema\customer.xsd
             -compiler C:\jdk142_04\bin\javac customer.xsdconfig
登入後複製

這個命令列的意思是告訴scomp生成customerXmlBean.jar,放在build目錄下,同時生成源代碼放在build\src下, Schema文件是customer.xsd,xsdconfig檔是customer.xsdconfig.其實, 生成的Java原始碼沒有太大作用,我們要的是jar檔.我們先看一下build\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.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();
    }
    }
登入後複製
###運行它,參考輸出結果:###
  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>
登入後複製
###  運行,開啟customers_new.xml:### 、利用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();
        }
   }
  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);
    }
登入後複製

运行,我们将会看到客户编号为3的客户的资料已经被删除.

  九、查询XML

  除了本文在以上讲述的,利用XMLBean能轻轻松松完成XML的读写操作外,结合XPath和XQuery,XMLBean还能完成象SQL查询数据库一样方便地查询XML数据. 关于XML查询以及如何创建XML数据库, 我将在另一篇文章里讨论.

  十、结束语

  XMLBean能帮助我们轻易读写XML,这将有助于我们降低XML的学习和使用,有了这个基础,开发人员将为学习更多地XML相关技术和Web Services,JMS等其他J2EE技术打下良好地基础.

 以上就是利用XMLBean轻轻松松读写XML的内容,更多相关内容请关注PHP中文网(www.php.cn)!


本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

能否用PowerPoint開啟XML文件 能否用PowerPoint開啟XML文件 Feb 19, 2024 pm 09:06 PM

XML檔可以用PPT開啟嗎? XML,即可擴展標記語言(ExtensibleMarkupLanguage),是一種廣泛應用於資料交換和資料儲存的通用標記語言。與HTML相比,XML更加靈活,能夠定義自己的標籤和資料結構,使得資料的儲存和交換更加方便和統一。而PPT,即PowerPoint,是微軟公司開發的一種用於創建簡報的軟體。它提供了圖文並茂的方

使用Python實現XML資料的合併與去重 使用Python實現XML資料的合併與去重 Aug 07, 2023 am 11:33 AM

使用Python實現XML資料的合併和去重XML(eXtensibleMarkupLanguage)是一種用於儲存和傳輸資料的標記語言。在處理XML資料時,有時候我們需要將多個XML檔案合併成一個,或移除重複的資料。本文將介紹如何使用Python實現XML資料的合併和去重的方法,並給出對應的程式碼範例。一、XML資料合併當我們有多個XML文件,需要將其合

Python中的XML資料轉換為CSV格式 Python中的XML資料轉換為CSV格式 Aug 11, 2023 pm 07:41 PM

Python中的XML資料轉換為CSV格式XML(ExtensibleMarkupLanguage)是一種可擴充標記語言,常用於資料的儲存與傳輸。而CSV(CommaSeparatedValues)則是一種以逗號分隔的文字檔案格式,常用於資料的匯入和匯出。在處理資料時,有時需要將XML資料轉換為CSV格式以便於分析和處理。 Python作為一種功能強大

使用Python實現XML資料的篩選和排序 使用Python實現XML資料的篩選和排序 Aug 07, 2023 pm 04:17 PM

使用Python實現XML資料的篩選和排序引言:XML是一種常用的資料交換格式,它以標籤和屬性的形式儲存資料。在處理XML資料時,我們經常需要對資料進行篩選和排序。 Python提供了許多有用的工具和函式庫來處理XML數據,本文將介紹如何使用Python實現XML資料的篩選和排序。讀取XML檔案在開始之前,我們需要先讀取XML檔案。 Python有許多XML處理函式庫,

使用PHP將XML資料匯入資料庫 使用PHP將XML資料匯入資料庫 Aug 07, 2023 am 09:58 AM

使用PHP將XML資料匯入資料庫引言:在開發中,我們經常需要將外部資料匯入到資料庫中進行進一步的處理和分析。而XML作為一種常用的資料交換格式,也常被用來儲存和傳輸結構化資料。本文將介紹如何使用PHP將XML資料匯入資料庫。步驟一:解析XML文件首先,我們需要解析XML文件,擷取所需的資料。 PHP提供了幾種解析XML的方式,其中最常用的是使用Simple

Python實作XML與JSON之間的轉換 Python實作XML與JSON之間的轉換 Aug 07, 2023 pm 07:10 PM

Python實作XML與JSON之間的轉換導語:在日常的開發過程中,我們常常需要將資料在不同的格式之間轉換。 XML和JSON是常見的資料交換格式,在Python中,我們可以使用各種函式庫來實作XML和JSON之間的相互轉換。本文將介紹幾種常用的方法,並附帶程式碼範例。一、XML轉JSON在Python中,我們可以使用xml.etree.ElementTree模

使用Python處理XML中的錯誤和異常 使用Python處理XML中的錯誤和異常 Aug 08, 2023 pm 12:25 PM

使用Python處理XML中的錯誤和異常XML是一種常用的資料格式,用於儲存和表示結構化的資料。當我們使用Python處理XML時,有時可能會遇到一些錯誤和異常。在本篇文章中,我將介紹如何使用Python來處理XML中的錯誤和異常,並提供一些範例程式碼供參考。使用try-except語句捕捉XML解析錯誤當我們使用Python解析XML時,有時候可能會遇到一些

Python解析XML中的特殊字元和轉義序列 Python解析XML中的特殊字元和轉義序列 Aug 08, 2023 pm 12:46 PM

Python解析XML中的特殊字元和轉義序列XML(eXtensibleMarkupLanguage)是一種常用的資料交換格式,用於在不同系統之間傳輸和儲存資料。在處理XML檔案時,經常會遇到包含特殊字元和轉義序列的情況,這可能會導致解析錯誤或誤解資料。因此,在使用Python解析XML檔案時,我們需要了解如何處理這些特殊字元和轉義序列。一、特殊字元和

See all articles