Home Backend Development XML/RSS Tutorial Use XMLBean to easily read and write XML

Use XMLBean to easily read and write XML

Mar 01, 2017 pm 05:05 PM
xml

1. About xml parsing

XML is becoming more and more important in java applications and is widely used in data storage and exchange. For example, our common configuration files are all stored in XML. XML is also used in technologies such as Java Message Service and Web Services for data exchange. Therefore, correctly reading and writing XML documents is the basis for XML applications.

Java provides two methods, SAX and DOM, for parsing XML, but Even so, it is not an easy task to read and write a slightly complex XML.

2. Introduction to XMLBean

Hibernate has become a popular object/relational database for Java environments. Mapping tools. Before the emergence of object/relational database mapping tools such as Hibernate, operations on the database were implemented through JDBC. For any operation on the database, developers had to write SQL statements themselves. The emergence of object/relational database mapping tools Finally, the operations on the database are converted into operations on JavaBeans, which greatly facilitates database development. Therefore, if there is a similar tool that can convert the reading and writing of XML into operations on JavaBeans, it will simplify the reading and writing of XML. Even developers who are not familiar with XML can easily read and write XML. This tool is XMLBean.

3. Prepare XMLBean and XML documents

XMLBean is an open source project of Apache, which can be downloaded from Download from http://www.apache.org, the latest version is 2.0. The directory after decompression is as follows:

xmlbean2.0.0
     +---bin
     +---docs
     +---lib
     +---samples
     +---schemas
Copy after login

In addition, you must prepare an XML document (customers.xml),

In this article In the example, we will read and write this document. The document source code is as follows:

<?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>
Copy after login

This is a customer data model. Each customer has a customer number (ID), name, and gender. , phone number (phoneNumber) and address, of which there are two addresses: primary address (PrimaryAddress) and billing address (BillingAddress). Each address consists of zip code, address 1, and address 2. The billing address also has the recipient Person (receiver). In addition, you must also prepare a configuration file (file name customer.xsdconfig). I will talk about the function of this file later. Its content is as follows:

<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>
Copy after login

4. XMLBean usage steps

The steps for using other object/relational database mapping tools for Java environments are the same. Before officially using XMLBean, we need to make two preparations.

1. Generate XML Schema file

 What is an XML Schema file? Normally, each XML file has a Schema file. The XML Schema file is an XML constraint file, which defines the structure and elements of the XML file, as well as the constraints on the elements and structure. Popular To put it simply, if an XML file is a record in a database, then Schema is a table structure definition.

Why is this file needed? XMLBean needs to know the structure and constraints of an XML file through this file, such as data types, etc. Using this Schema file, XMLBean will generate a series of related Java Classes to implement operations on XML. As a developer, you use the Java Classes generated by XMLBean to complete operations on XML without the need for SAX or DOM. How to generate What about this Schema file? For developers who are familiar with XML, they can write this Schema file themselves. For developers who are not familiar with XML, they can use some tools to complete it. The more famous ones such as XMLSPY and Stylus Studio can use XML files to write it. Generate Schema file. Add the Schema file (customer.xsd) we have generated:

  <?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>
Copy after login

2. Use scomp to generate Java Classes

scomp is a compilation tool provided by XMLBean, it is in bin directory. Through this tool, we can generate Java Classes.scomp from the above Schema file. The syntax of scomp is as follows:-

  scomp [options] [dirs]* [schemaFile.xsd]* [service.wsdl]* [config.xsdconfig]*
Copy after login

Main parameter description:

-src [dir] -- 生成的Java Classes存放目录
  -srconly -- 不编译Java Classes,不产生Jar文件
  -out [jarFileName] -- 生成的Jar文件,缺省是xmltypes.jar
  -compiler -- Java编译器的路径,即Javac的位置
  schemaFile.xsd -- XML Schema文件位置
Copy after login

 config.xsdconfig -- xsdconfig file The location of this file is mainly used to formulate some file name rules for the generated Java Class and the name of the Package. In this article, the package is sample.xmlbean

In this article, I ran it like this:

 scomp -src build\src  -out build\customerXmlBean.jar schema\customer.xsd
             -compiler C:\jdk142_04\bin\javac customer.xsdconfig
Copy after login

The meaning of this command line is to tell scomp to generate customerXmlBean.jar and place it in the build directory. At the same time, the source code is generated and placed under build\src. The Schema file is customer.xsd and the xsdconfig file is customer.xsdconfig. In fact, generate The Java source code is of little use, what we want is the jar file. Let's first take a look at the Classes generated under build\src\sample\xmlbean.

CustomersDocument.java -- 整个XML文档的Java Class映射
  CustomerType.java -- 节点sustomer的映射
  AddressType.java -- 节点address的映射
  BillingAddressType.java -- 节点billingAddress的映射
  PrimaryAddressType.java -- 节点primaryAddress的映射
Copy after login

Okay, now all our preparations have been completed Now let’s get to the point: using the jar file just generated to read and write XML.

5. Use XMLBean to read XML files

Create a new Java Project and download XMLBean2.0.0\lib\ The Jar file and the customerXmlBean.jar we just generated are added to the Project's ClassPath.

Create a new Java Class: CustomerXMLBean. The source code is as follows:

 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();
    }
    }
Copy after login

Run it and see the output result:

How about
  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
Copy after login

, is it very easy? The power of XMLBean.

6. Use XMLBean to write XML files

Using XMLBean to create an XML document is also a piece of cake. Let’s go back to Add a Method,

Please take a look at the 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();
        }
  }
Copy after login

Modify the 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();
    }
Copy after login

Run, open 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>
Copy after login

Seven , Use XMLBean to modify the XML file

We add another 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");
    }
Copy after login

After running, we will see that the lastname of the customer with customer number 3 has been changed to last.

8. Use XMLBean to delete a customer

Add another 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);
    }
Copy after login

运行,我们将会看到客户编号为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)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can I open an XML file using PowerPoint? Can I open an XML file using PowerPoint? Feb 19, 2024 pm 09:06 PM

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Using Python to merge and deduplicate XML data Using Python to merge and deduplicate XML data Aug 07, 2023 am 11:33 AM

Using Python to merge and deduplicate XML data XML (eXtensibleMarkupLanguage) is a markup language used to store and transmit data. When processing XML data, sometimes we need to merge multiple XML files into one, or remove duplicate data. This article will introduce how to use Python to implement XML data merging and deduplication, and give corresponding code examples. 1. XML data merging When we have multiple XML files, we need to merge them

Convert XML data to CSV format in Python Convert XML data to CSV format in Python Aug 11, 2023 pm 07:41 PM

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Filtering and sorting XML data using Python Filtering and sorting XML data using Python Aug 07, 2023 pm 04:17 PM

Implementing filtering and sorting of XML data using Python Introduction: XML is a commonly used data exchange format that stores data in the form of tags and attributes. When processing XML data, we often need to filter and sort the data. Python provides many useful tools and libraries to process XML data. This article will introduce how to use Python to filter and sort XML data. Reading the XML file Before we begin, we need to read the XML file. Python has many XML processing libraries,

Import XML data into database using PHP Import XML data into database using PHP Aug 07, 2023 am 09:58 AM

Importing XML data into the database using PHP Introduction: During development, we often need to import external data into the database for further processing and analysis. As a commonly used data exchange format, XML is often used to store and transmit structured data. This article will introduce how to use PHP to import XML data into a database. Step 1: Parse the XML file First, we need to parse the XML file and extract the required data. PHP provides several ways to parse XML, the most commonly used of which is using Simple

Python implements conversion between XML and JSON Python implements conversion between XML and JSON Aug 07, 2023 pm 07:10 PM

Python implements conversion between XML and JSON Introduction: In the daily development process, we often need to convert data between different formats. XML and JSON are common data exchange formats. In Python, we can use various libraries to convert between XML and JSON. This article will introduce several commonly used methods, with code examples. 1. To convert XML to JSON in Python, we can use the xml.etree.ElementTree module

Handling errors and exceptions in XML using Python Handling errors and exceptions in XML using Python Aug 08, 2023 pm 12:25 PM

Handling Errors and Exceptions in XML Using Python XML is a commonly used data format used to store and represent structured data. When we use Python to process XML, sometimes we may encounter some errors and exceptions. In this article, I will introduce how to use Python to handle errors and exceptions in XML, and provide some sample code for reference. Use try-except statement to catch XML parsing errors When we use Python to parse XML, sometimes we may encounter some

Python parsing special characters and escape sequences in XML Python parsing special characters and escape sequences in XML Aug 08, 2023 pm 12:46 PM

Python parses special characters and escape sequences in XML XML (eXtensibleMarkupLanguage) is a commonly used data exchange format used to transfer and store data between different systems. When processing XML files, you often encounter situations that contain special characters and escape sequences, which may cause parsing errors or misinterpretation of the data. Therefore, when parsing XML files using Python, we need to understand how to handle these special characters and escape sequences. 1. Special characters and

See all articles