Read and write xml using XMLBean

2010-03-29  来源:本站原创  分类:Java  人气:494 

1, on the XML parsing XML in Java applications were becoming increasingly important, widely used in data storage and exchange. For example, our common configuration files are stored in XML-mode. XML is also used in Java Message Service and Web Services and other technology as a data exchange.

Therefore, the correct read and write XML documents are XML-based applications.

Java provides two ways for the SAX and DOM parsing XML, but even so, a little bit complicated to read and write XML, is not an easy task.

2, XMLBean About Hibernate has become the popular Java-oriented environment, object / relational database mapping tool.

In the Hibernate and other object / relational database mapping tool before the advent of the database operation is achieved through JDBC, any operation on the database, developers have to write your own SQL statement to achieve. Object / relational database mapping tool appears, right the operation of the database to switch pairs JavaBean operation, greatly facilitate database development. So if there is a similar tool to be able to achieve would be to switch pairs JavaBean to read and write XML, the operation would simplify the reading and writing XML, even for XML The developers are not familiar with can be easily read and write XML. This tool is XMLBean.

Third, to prepare XMLBean and XML documents XMLBean is an open source project Apache can be downloaded from http://www.apache.org, the latest version is 2.0. Unzip your directory is as follows:
xmlbean2.0.0
+ --- bin
+ --- docs
+ --- lib
+ --- samples
+ --- schemas

Furthermore, we need to prepare an XML document (customers.xml), the example in this article, we will read and write operations in this document. Document Source 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>

(Here we must note that software will not generate the xml schema in xml file when adding the information, it is best to empty file)
This is a customer's data model, each customer has a customer number (ID), name, sex (gender), telephone number (phoneNumber) and address, which address is twofold: first address (PrimaryAddress) and billing address ( BillingAddress), each address with zip code, address 1, and address the composition of two. of which there are billing address the recipient (receiver).

Addition, we must prepare a configuration file (the file name customer.xsdconfig), the role of the document behind me would say that it reads 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>

(This itself was mainly defined package)
4, XMLBean the use of the steps, and other Java-oriented environment, object / relational database mapping tools, like the use of the steps in the official use of XMLBean ago, we have to make two to prepare.

1. Generate the XML Schema file What is the XML Schema file? Under normal circumstances, each XML file has a Schema files, XML Schema file is an XML-binding document, which defines the structure and elements of XML documents. As well as elements and structural constraints. More simply, if the XML file is a database record, then the Schema is the table structure definition.

Why do we need this file? XMLBean need this file to know the structure of an XML file, as well as constraints, such as data types. Take advantage of this Schema file, XMLBean will produce a series of related Java Classes to achieve the right XML operation. As a developer , it is the use of XMLBean generated Java Classes to complete the operation on the XML without the need for SAX or DOM.

How will this Schema documents? If you are familiar with XML, developers can write their own this Schema files, that are not familiar with XML, developers can be accomplished through a number of tools.

More well-known, such as XMLSPY and Stylus Studio are available through XML file to generate the Schema file. Join us in this Schema file has been generated (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 used to generate Java Classes

scomp is provided XMLBean a compilation tool, its bin directory. With this tool, we can more than Schema file generation Java Classes.

scomp The syntax is as follows: --

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

The main parameters Description:
-src [dir] - the generated Java Classes storage directory-srconly - does not compile Java Classes, does not produce Jar file-out [jarFileName] - the generated Jar file, the default is xmltypes.jar
-compiler - Java compiler path, that is, Javac position schemaFile.xsd - XML Schema File Location config.xsdconfig - xsdconfig file, this file is mainly used to develop the generated Java Class
Some of the file name rules and the name of the Package, in this paper, package is sample.xmlbean

In this article, I was running like this:
scomp-src build \ src-out build \ customerXmlBean.jar schema \ customer.xsd
-compiler C: \ jdk142_04 \ bin \ javac customer.xsdconfig
(Here note that, on an inside javac location if there is a folder name with spaces is not successful, then need to order
N: \ Development commonly used packages \ xmlbeans-2.5.0 \ bin> subst w: "E: \ Program Files \ Java \ jdk1.6.0_02"

N: \ Development commonly used packages \ xmlbeans-2.5.0 \ bin> scomp-out build \ productionsXmlBean.jar productions.xsd-compiler w: \ bin \ javac productions.xsdconfig
These are my orders to the folder with spaces to replace)
This means that the command line to tell scomp generated customerXmlBean.jar, on the build directory, while generating the source code on the build \ src under, Schema file is customer.xsd, xsdconfig file is customer.xsdconfig.

In fact, the generated Java source code is not much of a role, we need the jar file. We turn first to build \ src \ sample \ xmlbean under the generated Classes.
CustomersDocument.java
- The entire XML document Java Class mapping CustomerType.java
- Node sustomer mapping AddressType.java
- Node address mapping BillingAddressType.java
- Node billingAddress mapping PrimaryAddressType.java
- Mapping the node primaryAddress Well, all of our preparations for this work has been completed. Here's begun to enter the main points: the use of generated jar file just to read and write XML.

5, using XMLBean reading XML file to create a new Java Project, will be XMLBean2.0.0 \ lib \ under the Jar file and the generated customerXmlBean.jar we have just added to the Project, ClassPath.

Create a new Java Class: CustomerXMLBean. 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();
    }
    }

To run it, see the output:
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
How kind, is not it easy? XMLBean power.

6, using XMLBean write XML files to create an XML document using XMLBean is an easy task. We have to add a Method,
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();      }   }
 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();
    }

running, open the 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>

7, using XMLBean modify the XML file we have to add a 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");    }
 After you run  , We will be able to see the customer numbers 3 customers lastname has changed to last  .
   
 8. delete a customer utilizing XMLBean
   
 An additional 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);
    }

Running, we will see customer number for the three customer information has been deleted.

(Note that the xsd file is written, there are problems automatically generated)

Source: http://java.chinaitlab.com/XMLBeans/38498.html

相关文章
  • Read and write xml using XMLBean 2010-03-29

    1, on the XML parsing XML in Java applications were becoming increasingly important, widely used in data storage and exchange. For example, our common configuration files are stored in XML-mode. XML is also used in Java Message Service and Web Servic

  • 使用JSP + JAVABEAN + XML 开发的一个例子 2014-12-30

    本例子是参考了一些网站上有关JSP 对 XML 的操作的相关文档,又结合了一些个人的体会.例子涉及的内容是,开发的一个企业内部定餐系统后台管理端的部分代码,功能主要集中在对于餐馆基本信息的管理. 该例子本身开发的起因是我在原公司和同事们一个玩笑的一部分.特此也表达对那些一起共事的朋友们的想念. 例子本身是在TOMCAT4.01 平台下运行的B/S结构的程式.有关TOMCAT 的配置,这里不做说明.只讲解一下相关文件及文件夹的目录结构. 目录结构说明: /tomcat/webapps/canyin

  • XMLBEANS Learning xsd schema 2010-03-29

    1, on the XML parsing XML in Java applications were becoming increasingly important, widely used in data storage and exchange. For example, our common configuration files are stored in XML-mode. XML is also used in Java Message Service and Web Servic

  • XMLBEANS use of summary 2011-01-14

    This is just a few days of schema file to generate javabean, then through javabean generation, modify, and delete XML, hereby record: Transfer from the article: http://xiejiangbo.javaeye.com/blog/582581 First, on the XML parsing XML in the Java appli

  • xmlbean generated jar with packet path 2009-11-16

    Xmlbean generated using jar found this article in turn as a record of their own learning. When our preliminary understanding of XSD, we have been able to create the XML BEAN. To create XML BEAN, need to make the following preparations: (1) Download X

  • spring3.0 completely replace the use of annotation XML (continued) 2010-09-02

    Others did not give a previous article, did not think a delay is 2 weeks, why they are opening a separate bar. From a reply to reaction, most people do not agree completely replace the XML, this exception is that in expected. I personally still prefe

  • JavaBean转XML pojoxml 2013-04-28

    pojoxml 网站 : https://code.google.com/p/pojoxml/ PojoXML JAVABean 与XML相互转换的工具,有点像XMLBean.但是更轻量级. 示例代码: POJO Class public class Employee{ private String name; private int age; public String getName(){ return name; } public int getAge(){ return age; } .

  • Spring3 MVC Restful 多请求类型(json,xml,k-v),多视图配置(J... 2011-09-15

    beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"

  • Hibernate.cfg.xml configuration file (including the primary key generation strategy Introduction) 2009-02-27

    Hibernate.cfg.xml configuration file: <? xml version = "1.0" encoding = "utf-8"?> <! DOCTYPE hibernate-configuration PUBLIC "- / / Hibernate / Hibernate Configuration DTD / / EN" "hibernate-configuration-2.0.dtd

  • Unable to load bean: type: struts-derfault.xml abnormal 2009-03-01

    Struts2 in the use of a lot of friends from time to time we encountered this anomaly, leading to its main reason is because the wrong package, we have to be xwork-2.1.1.jar and struts2-core-2.1.2.jar, replaced xwork-2.0. 4.jar and struts2-core-2.0.14

  • Properties with 6 supplementary hibernate.cfg.xml configuration 2009-03-01

    In some special circumstances, we may be saved in the database connection information config.properties document, for example, make a install.jsp to modify config.properties documents, implementation of online information on the database configuratio

  • Pring Beanfactory at the jsp, servlet, web.xml and other configuration 2009-03-03

    Keywords: spring beanfactory Spring in the web application called the Beanfactory 1) Configure web.xml Java code <? xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE web-app PUBLIC "- / / Sun Microsystems, Inc. / / DTD

  • hibernate.cfg.xml configuration collection 2009-04-09

    <? xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-configuration PUBLIC "- / / Hibernate / Hibernate Configuration DTD 3.0 / / EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&

  • ajax the dom of access to xml tags 2009-04-25

    The following shows how to use the dom to get to from the service returns an XML DOM object, and get the XML document you want to get tag, a tag of child label, the label's content or very simple <?xml version="1.0" encoding="UTF-8"

  • JavaScript html js 2 linkage regions, provinces and cities in the secondary linkage, provincial cities and counties js + xml 3 linkage 2009-05-06

    Comparison of two best linkage: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> New Document </TITLE> <META NAME="Generator" CONTENT="EditPlus"> <MET

  • DWR.xml configuration file specification 2009-05-24

    1, set up configuration files dwr.xml Dwr.xml any of the required documents are included in the statement DWR DOCTYPE line in the following format: <! DOCTYPE dwr PUBLIC "- / / GetAhead Limited / / DTD Direct Web Remoting 1.0 / / EN" "ht

  • dwr configuration file dwr.xml 2009-06-26

    I dwr Chinese document on a collation do dwr.xml purely jobs they take, there are useful do not forget to top friend you, leave a contact with the exchange of learning! Welcome to my site to exchange technical www.ithuzhu.com dwr.xml is the DWR confi

  • My eclipse5.5 add xml template 2009-07-22

    There are only four Myeclipse5.5 template xml 1, Default XML template, 2, XML template for a web.xml, 3, XML template for a web.xml file with Struts, 4, XML template for a struts-config.xml If we want to create a new xml file, but not so this time wh

  • hibernate.cfg.xml 2009-07-25

    <? xml version ='1 .0 'encoding =' UTF-8 '?> <! DOCTYPE hibernate-configuration PUBLIC "- / / Hibernate / Hibernate Configuration DTD 3.0 / / EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <! - G

  • 5 SSH package: Hibernate.cfg.xml from Spring management, use services, services in the servic 2009-08-02

    SSH package in the basis of the four SSH package was revised to five 5 SSH package: Hibernate.cfg.xml from Spring management, use services, services in the service layer *** Note: SSH package combination of the four programs in the SSH add a layer of