Getting started with XML data and documents using XMLBeans

Source: Internet
Author: User
Tags rar ibm developerworks
Getting started with XML data and documents using XMLBeans

Time: 2004-03-03
Author: powerise1
Number of Views: 2603
This article keyword: xml, XMLBeans, ant, schema
Article Tools
recommend to a friend
Print Article
XMLBeans is a project at BEA company for accessing and processing data and documents. Using XMLBeans allows you to treat and process XML data and documents in an object-oriented way, while being faithful to the XML structure and schema of the XML data. The author of this article briefly introduces XMLBeans, and gives a simple example, detailing how to configure XMLBeans to make it work properly.

XMLBeans from Bea is a breakthrough in accessing and processing XML data and document Technologies using Java technology.                                 For the first time, developers can look at XML data in their familiar, user-friendly, object-oriented view, while accessing the corresponding structure and schema of the data. --An introduction to XMLBeans from Bea

XMLBeans is a BEA project for XML processing that is now available for free download and use, with the latest version being 1.0. 1 Why use XMLBeans

Before XMLBeans, we have two options for accessing XML data and documents:

1. Use DOM, sax to access the contents of XML data and documents

2. Using techniques such as JAXB to map XML to Java classes

No matter which one you use, you cannot fully access the rich content and schema information of the XML data and objects. Because of the mismatch between the Java data Model and the XML, you can either opt for extensibility or simply select the robustness of the system.

With the advent of XMLBeans, we do not need to take such a compromise measure again. XMLBeans provides additional features to access XML data and documents:

1. XMLBeans is based on a tag stream, so it is easy to use pointers to navigate between XML data and documents. The pointer interface applies to all XML data and documents.

2. If your XML data and documents have a schema, XMLBeans will give you the Java class "view" of the XML data and documents (that is, the Java code that accesses the XML data and documents).

3. Developers can use these Java code to easily read/write XML data and documents, and are forced to execute some of the constraints specified in the XML schema.

4. The Java class "view" can faithfully express the contents of raw XML data and documents, because the Java class "View" is based on protected, most basic XML representations.

So the benefits of using XMLBeans to access XML data and documents are obvious:

1. Use an object-oriented perspective to view and process data and documents entirely

2. Developers no longer need to write large amounts of code to access XML data and documents

3. You can use the constraints on the data defined in the schema without having to write the code that implements the constraints yourself

4. There is no need to parse all the XML data and documents but only to access one of the data items

For more details on XMLBeans please visit 2 environment and tool preparation

A lot of work in XMLBeans uses the Ant tool, so download the ant tool and keep it running before you start working.

XMLBeans Java implementation please go to Bea's website to download:

During execution, you also need to use the DOM component that accesses XML, that is, the Xml-apis.jar file, which can be downloaded to the This jar file is also available in the Test-xmlbeans.rar file in the attachment. 3 First example 3.1 Example Description

Here we use an example of an order, and his example document is as follows:

<po:purchase-order xmlns:po= "Http://" >


<po:name>gladys kravitz</po:name>

<po:address>anytown, pa</po:address>




<po:description>burnham ' s Celestial Handbook, vol. 1</po:description>






<po:description>burnham ' s Celestial Handbook, vol. 2</po:description>










We use the following schema to describe this instance document:


Xmlns:xs= "Http://"

xmlns:po= "Http://"

Targetnamespace= "Http://"

elementformdefault= "qualified" >

<xs:element name= "Purchase-order" >



<xs:element name= "Customer" type= "Po:customer"/>

<xs:element name= "Date" type= "Xs:datetime"/>

<xs:element name= "Line-item" type= "Po:line-item" minoccurs= "0" maxoccurs= "unbounded"/>

<xs:element name= "Shipper" type= "Po:shipper" minoccurs= "0" maxoccurs= "1"/>




<xs:complextype name= "Customer" >


<xs:element name= "name" type= "xs:string"/>

<xs:element name= "Address" type= "xs:string"/>


<xs:attribute name= "Age" type= "Xs:int"/>


<xs:complextype name= "Line-item" >


<xs:element name= "description" type= "xs:string"/>

<xs:element name= "per-unit-ounces" type= "Xs:decimal"/>

<xs:element name= "Price" type= "Xs:decimal"/>

<xs:element name= "Quantity" type= "Xs:integer"/>



<xs:complextype name= "Shipper" >


<xs:element name= "name" type= "xs:string"/>

<xs:element name= "Per-ounce-rate" type= "Xs:decimal"/>




Now that the XML data to be accessed has been identified, and the schema has been used to describe him, the rest is to use XMLBeans to assist in generating Java code to access the XML data, which is described in detail in the following sections 3.2 Ant helper generates Java code 3.2.1 External jar files that access XML data

When using XMLBeans to generate Java code to access XML data, we need to use the Xbean.jar file, which is in the download XMLBeans. 3.2.2 Increase in taskdef

When compiling script execution, you must add a Xmlbean taskdef that reads as follows:

<taskdef name= "Xmlbean" classname= "Com.bea.xbean.tool.XMLBean" classpath= "Path/to/xbean.jar"/> 3.2.3 Xmlbean

Using the Xmlbean tag to generate Java code to access the XML data, a simple example is as follows:

<xmlbean schema= "schemas" destfile= "Schemas.jar"/>

<xmlbean schema= "schemas/easypo.xsd" destfile= "Schemas.jar" srcgendir= "/>".

The first example is to generate access code for all the *.xsd files below schemas, compile all the code and put it into the Schemas.jar file.

The second example is to generate access code for all easypo.xsd files below schemas, to compile all the code and put it into the Schemas.jar file, which will be generated. The Java file is placed in the current directory.

A simple description of the parameters is as follows:

The Xmlbean label indicates that this is the access code to generate the specified schema file.

The Schema attribute represents the scope of the XSD file to generate access code, can be a directory, or

is a file or is defined using Fileset.

The DestFile property defines that the generated code will be placed in that file when it is compiled.

The Rcgendir property represents the generated. The Java file will be placed in that directory.

Other parameters supported by the Xmlbean tag and related instructions refer to the Help documentation for XMLBeans, which is not overly described here. 3.2.4 the actual build.xml

<project name= "MyProject" default= "Compile" basedir= "." >

<property name= "src" value= "." />

<property name= "Build" value= "Build"/>

<property name= "Dist" value= "dist"/>

<property name= "Classpath" value= "/xkit/lib/xbean.jar"/>

<target name= "Init" >

<!--Create The build directory structure used by compile-->

<mkdir dir= ""/>


<target name= "Compile" depends= "init" >

<!--Compile the Java code from into-->

<taskdef name= "Xmlbean" classname= "Com.bea.xbean.tool.XMLBean" classpath= ""/>

<xmlbean schema= "schemas/easypo.xsd" classpath= "destfile=" Easypo.jar "srcgendir=" "/>"


</project> 3.2.5 generate jar files

Now you can enter the directory where the Build.xml file resides and execute ant-f build.xml to generate all the code that accesses the Easypo.xml.

After execution, a Schemas.jar file is included in this directory, and he contains all the. class files that were generated and compiled to access the XML document. A net directory is included under the directory, and his subdirectory contains all the generated. java files. The actual jar file composition please refer to the Schemas.jar file provided by the author. 4 test . 4.1 test Code

OK, now let's write an example to test whether the XML data can be accessed successfully. Complete code refer to

Parse XML instance document, his parameter pofile is a parameter of a file type

So we need to save 3.1 of the instance document as an. xml document

PurchaseOrderDocument Podoc =

PurchaseOrderDocument.Factory.parse (Pofile);

Create an interface to access the XML instance document PurchaseOrder

/**[ note] to the author 's surprise, the definition of this paragraph in the example code provided by Bea is as follows:

*PurchaseOrder PO = podoc.getpurchaseorder ();

* That means PurchaseOrder . This interface should be a separate class, but the author looks at the XMLBeans

* the last generated. Java in the file, this purchaseorder but as a purchaseorderdocument . of a

* an inner class appears.


Purchaseorderdocument.purchaseorder po = podoc.getpurchaseorder ();

Directly past all the contents of all the LineItem child elements, he returns an array of LineItem objects.

lineitem[] LineItems = Po.getlineitemarray ();

System.out.println ("Purchase order has" + Lineitems.length + "line items.");

Double totalamount = 0.0;

int numberofitems = 0;

Use the corresponding get method directly to obtain the value of the corresponding property

for (int j = 0; J < Lineitems.length; J + +)


SYSTEM.OUT.PRINTLN ("line item:" + j);

System.out.println (

"Description:" + lineitems[j].getdescription ());

System.out.println ("Quantity:" + lineitems[j].getquantity ());

System.out.println ("Price:" + lineitems[j].getprice ());

Numberofitems + + lineitems[j].getquantity (). Intvalue ();

TotalAmount + + Lineitems[j].getprice (). Doublevalue () * lineitems[j].getquantity (). Doublevalue ();


System.out.println ("Total items:" + numberofitems);

SYSTEM.OUT.PRINTLN ("Total amount:" + totalamount); 4.2 Test Results

To run this code, you should print the following information on the console:

Purchase Order has 3 line items.

Line item 0

Description:burnham ' s Celestial Handbook, vol. 1



Line Item 1

Description:burnham ' s Celestial Handbook, vol. 2



Total Items:4

Total amount:41.68 5 Summary

XMLBeans is a Microsoft Open source project, a schema based, access to XML solution, providing access to and processing of XML data and documents can be fully access to the content of XML, without losing the XML schema information powerful features. Using XMLBeans allows you to treat and process XML data and documents in an object-oriented way, while being faithful to the XML structure and schema of the XML data.

The author of this article briefly introduces XMLBeans, and gives a simple example that details how to configure XMLBeans, how to use his ant extension to help generate Java code to access XML, and how to write a client to test the success of that piece of code. Hope that we can master how to use XMLBeans to simplify their development work, improve their development speed. The advanced application of XMLBeans will be covered in the following articles.


1. Ant's Help

2. XMLBeans's help

Tools Download:

1. Ant tool Download

2. XMLBeans Download

All working papers of the author: Test-xmlbeans.rar

Author Information:

Name: Shao

Contact Way: 0731-6665772,

Introduction to

: The author is currently a software engineer of Software center of Computer System Integration Co., Ltd. of Changsha Railway Institute of Hunan Province, IBM Developerworks/bea Dev2dev contributor, mainly research Java EE programming technology, WEB Service technologies and their implementations on Websphere, WebLogic, and Apache platforms, with IBM's developing with Websphere Studio certificate. You are welcome to visit the author's personal website:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.