Zeus implementation of Xml-java data binding

Source: Internet
Author: User
Tags format object definition bind cdata interface string version
xml| data Zeus Implementation of XML-JAVA data binding

Zhongjiahao (judson78@yahoo.com.cn)

March 2003

Zeus can bind Java objects to XML files, binding makes it easier to use data in Java EE. This paper mainly introduces the compiling and using of Zeus. The DTD and XML files used during the binding process are also described.
1 Zeus Profile
Enhydra is the name of a non-profit organization named after a small otter that grows on the coast of California. Unlike the famous Apache, Enhydra is dedicated to the study of E-business solutions around application server. Zeus is one of the many tool software developed by Enhydra, which is the function of data binding to Javaobject and XML. It converts any XML file into a corresponding javaobject file, and transforms the data conveniently between the two forms. Zeus the latest version is Zeus1.0 Beta 3.5, because it is completely open source, you can download the source code after the http://zeus.enhydra.org/software/downloads/index.html to compile their own.

2 Preliminary knowledge

2.1 Using XML as Data carrier
XML (extensible Markup Language) is developed by the consortium and is supported by almost all of the world's largest companies. XML is a very flexible text format that, compared with HTML, continues its simple, understandable syntax, but with greater flexibility and scalability. Example 1 is an XML file that describes the customer information, and as a language for describing the data, the organization of the XML is free and articulate.

<?xml version= "1.0" encoding= "GBK"?>
<customer customer_no= "00001" >
< name> li June </name>
<Id_No>210106421016001</Id_No>
<sex > Men </Sex>
<Birth_Place> Dalian </Birth_Place>
<Birth_Date>1942-10-16</Birth_Date>
<Nationality> China </Nationality>
<Education> High School </Education>
<Address> Dalian Shahekou </Address>
<contact_info Id = "00001" >
<Zip_Code>116001</Zip_Code>
<Tel_No>2645677</Tel_No>
</Contact_Info>
</Customer>



Example 1: Describing the customer's XML file

This XML structure is clear: Describes a "customer" entity, which has attributes: Name, ID number, sex, place of birth, birthday, place of birth, contact (ZIP code, telephone), etc.

The first line <?xml version= "1.0" encoding= "GBK"?> describes the version of this XML file as 1.0, with the "GBK" encoding (if you want to parse Chinese, GBK or GB2312 is necessary). <customer customer_no= "00001></customer> make up the complete" root tag "of the file, Customer_no is the" properties "of the Customer tag, <name></ Name>, <Nationality></Nationality> are child tags of <Customer>. In < Contact></contact>, you can also continue to include child tags:<zip_code>, <Tel_No>. The XML language of user-defined tag gives users enough freedom to represent data, but it also makes it difficult to display and parse, in order to solve this problem, the world-view system restricts XML in format control and tag definition. For example, <customer></Customer> is a pair of unqualified tokens.

2.2 DTD definition Data
The purpose of a DTD (Document Type definition) is to define the relationships between elements and elements in an XML document. A DTD can exist in a single file with the XML to which it is applied, or it can be a separate file. Example 2 is a DTD file that describes the XML file described in Example 1.

<?xml version= "1.0" encoding= "GBK"?>
<! ELEMENT Customer (name?,id_no?,sex?,birth_place?,birth_date?,nationality?, education?, contact_info?>
<! Attlist Customer
Customer_no CDATA #REQUIRED
>
<! ELEMENT Name (#PCDATA) >
<! ELEMENT id_no (#PCDATA) >
<! ELEMENT Sex (#PCDATA) >
<! ELEMENT birth_place (#PCDATA) >
<! ELEMENT birth_date (#PCDATA) >
<! ELEMENT Nationality (#PCDATA) >
<! ELEMENT Education (#PCDATA) >
<! ELEMENT contact_info (zip_code?,tel_no?) >
<! Attlist Contact_info
ID CDATA #REQUIRED
>
<! ELEMENT Zip_Code (#PCDATA) >
<! ELEMENT tel_no (#PCDATA) >



Example 2:dtd file

Rogue radius, Example 2 of the DTD file defines the customer element of example 1 of the XML description, through the definition of the DTD, the markup in the XML is given meaning, and the relationship between the customer and other elements is well explained. The existence of a DTD file gives the data in XML a prescribed form, which is easily associated with another important way of data organization--the fields and data in a database table. Dtd-xml This kind of structure with table structure-data, which provides a natural convenience for the conversion of the two technologies, makes it easy to express the data in the table in XML with the help of the DTD.

3 Compiling your Zeus.
Downloaded Zeus is a zip file, if you choose to download the source code, you must first compile to be able to use. This article introduces the use of Zeus, first from the source code compiled.

The compiled method is described in detail in the Downloaded Docs folder, and as part of the Java technology Camp, Zeus has also used some of the other outstanding Java tools to dedicate himself fully. For example, the compiler uses Apache Ant. The Ant.jar file can be found under Zeus\lib.

The only thing to do before compiling is to set the operating system's java_home environment variables. For example, in a Windows system, run set Java_home = d:/jdk1.3.1 If the JDK is installed in d:/jdk1.3.1. When you have finished your preparation, you can start compiling zeus,ant itself is an easy-to-use compilation tool, Build.xml files can be set up with all the compilation details and file assembly. Zeus's compiled files are located in the root directory of Build.xml, which contains all the details of compiling and assembling Zeus.jar files for Zeus and is highly readable.

Determine that under the root directory of Zeus, run./bin/build.bat targets,ant can find build.xml files located in the current directory, and if you do not enter any arguments, ant will output a prompt for you to enter the compilation targets:

Compile: Compile all the source code of Zeus and place it under build\classes;
Bin: The original src\bin under the file to Build\bin under the original Lib directory of the jar file under Build\lib and the combination of good Zeus.jar placed in this folder;
Doc: Compile Javadoc and handcuff the results to bin\docs\apidoc\.

Sample and test are used for compiling routines and testing code, respectively. If you do not want to compile one step at a time, you can set the Targers parameter to all so that ant will automatically compile all the targets for you in the correct order. After compiling, a build folder appears, and all the compiled files are in this file. Check the Build/bin folder, the Zeus.jar file that appears is the compiled tool. If you have enough experience to modify Zeus source code and Build.xml files, you can create your own Zeus.

4 generating Java objects that describe XML
The first step in building a Java object is to use Zeus to generate Java source code automatically. Using the Zeus batch file in Build\bin\ 's Zeus.bat, the syntax is as follows:

zeus.bat-constraints=
[-outputdir=]
[-collapsesimpleelements=]
[-ignoreidattributes=]
[-javapackage=]
[-root=]

The parameters are explained as follows:

Parameter must be a default value description
Constraints Yes No constraint file (DTD or XSD. file) is specified that produces Java code
OutputDir No The current directory places the root directory of the generated Java file
Collapsesimpleelements no False supports the simplification of simple elements, the so-called "simple element" is an element of no attributes (attribute) that is described in a DTD file. If such a simple element is Zeus resolved in a "thin" form, the generated Java class uses the form of its parent element's Get[elementname] () to get the value of that element in the XML, in a form that is more than the normal Get[elementname] (). The form of getcontent () is more convenient. It also reduces the number of unnecessary generation classes.
Ignoreidattributes No False This parameter sets the criteria for determining the "simple element": whether to use the id attribute as a condition. Setting this argument to true causes those elements with only one "id" attribute to be considered "simple elements"
Javapackage No packages that specify the generated Java class. For example, when Com.zjh.tools is specified, all generated Java classes are within the Com.zjh.tools package.
Root No is determined by the DTD parser to determine the root element for resolution. When parsing a DTD file with multiple top-level elements, specify the root element to generate the correct Java class.

To continue with the example above, bind the example 1 XML file to the Java objects, and the first step is to generate Java files, The specific solution is to use the org.enhydra.zeus.util.DTDSourceGenerator in Zeus.jar, Example 2 of the Customer.dtd file as a necessary constrains parameter. First execute the following command:

Place the customer file under the C:\zeus\dtd file, establish the C:\zeus\zjhsample, and execute the following command:
C:\zeus>.\build\bin\zeus.bat-constraints=dtd\customer.dtd-outputdir=zjhsample-javapackage = Com.zjh.zeustest.binding-collapsesimpleelements=true

View the C:\zeus\zjhsample\com\zjh\zeustest\binding folder and found that six files were generated: Customer.java, Customerimpl.java, Contact_info.java, Contact_infoimpl.java, Customerunmarshaller.java, Unmarshallable.java.

The generated class name is regulated: Customer, Contact_info is the name of a simple element in a DTD file, Zeus generates an interface with the same name, and Customerimpl, Contact_infoimpl is the class that implements the two interfaces. Customerunmarshaller and Unmarshallable look a little strange, But it doesn't come out of nowhere: The Unmarshallable interface inherits from the Org.xml.sax.ContentHandler, provides an interface for parsing XML legality, and all Elementimpl classes inherit the interface; Customerunmarshaller provides the reverse decoding XML. interface, enter the XML file and return to the Customer object.

All the secrets of data binding are hidden in these files and can be edited with any text editor. However, as stated in the program declaration: Modifying these programs may cause data-binding operations to fail.

Finally compile the six Java files: Javac *.java, generating class files. This allows you to get a Java class that describes the XML file.

5 Marshal and Unmarshal--xml and the conversion of Java object
Universal XML files are suitable for data transfer between different technology platforms, Java objects can provide a more convenient interface for Java programs, Java object generated through the Zeus tool is like a bridge, which ties the two tightly together (see Figure 1). Not only does it build enough attributes to describe the values of each element of an XML file, but it also provides an interface that converts Java objects to XML files: Unmarshal and Marshal.

Unmarshal: "Reverse decoding" XML file as Javaobject;

Marshal: "Decode" javaobject as an XML file.

Graph 1:java object and XML file conversion

5.1 unmarshal XML files to Java objects
Once a Java object generated with Zeus is compiled, translating an XML file into a Java-style representation becomes a simple and satisfying thing. This process is described as "reverse decoding (Unmarshal)", which is the Unmarshal () method of the Elementimp object generated Zeus based on the DTD file. Like a science fiction article automatic manufacturing machine, to the Unmarshal method into the Java file, Writer, or inputstream packaging of XML files, a press the Unmarshal button, XML data Java representation is easily born. The Customerunmarshal class in the sample program (example 3) completes the work of Customerinfo.xml in unmarshal Example 1 and outputs the results to the screen.

Package com.zjh.zeustest;
Import java.io.*;
Import com.zjh.zeustest.binding.*;

public class CustomerInfo {
public static void Main (string[] args) {
if (args.length!=1) {
System.out.println ("" "Please" "Location of XML file");
Return
}
try{
Customer customer = Customerunmarshaller.unmarshal (new File (Args[0)), false);
System.out.println ("Name:" +customer.getname ());
SYSTEM.OUT.PRINTLN ("Certificate number:" +customer.getid_no ());
System.out.println ("Sex:" +customer.getsex ());
System.out.println ("Birthplace:" +customer.getbirth_place ());
System.out.println ("Nationality:" +customer.getnationality ());
System.out.println ("Education:" +customer.geteducation ());
System.out.println ("Zip code:" +customer.getcontact_info (). Getzip_code ());
SYSTEM.OUT.PRINTLN ("Phone Number:" +customer.getcontact_info (). Gettel_no ());
}catch (Exception e) {
E.printstacktrace ();
}
}
}



Example 3 Unmarshal XML

After compiling the program, run with the following command:
Java-classpath. \ n.. \lib\xerces.jar Com.zjh.zeustest.Customer Unmarshal. \cust.xml

Enter the following:

Name: Li June
Certificate number: 210106421016001
Sex: Male
Place of birth: Dalian

Nationality: China
Education: High School
Post code: 116001
Phone Number: 2645677



5.2 Marshal Java objects to XML files
The conversion of data from Java object to XML file is a unmarshal inverse process, and is semantically marshal (decoding) the term. The example provided below (example 4) provides a complete example of a data binding use:

Read the Cust.xml into
Unmarshal XML
Modifying a property value for a Java object
Marshal Java objects

Package com.zjh.zeustest;
Import java.io.*;
Import com.zjh.zeustest.binding.*;

public class Customermarshal {

public static void Main (string[] args) {
if (args.length!=1) {
System.out.println ("" "Please" "Location of XML file");
Return
}
try{
Customer customer = Customerunmarshaller.unmarshal (new File (Args[0)), false);
Contact_info ContactInfo = Customer.getcontact_info ();
Contactinfo.setid ("0002");
Contactinfo.setzip_code ("116001");
Contactinfo.settel_no ("6656456");
Customer.setbirth_date ("1979-10-1");
Customer.setbirth_place ("Dalian");
Customer.setcontact_info (ContactInfo);
Customer.setcustomer_no ("1234566");
Customer.seteducation ("university");
Customer.setid_no ("210204197910012233");
Customer.setname ("Li Ming");
Customer.setnationality ("China");
Customer.setsex ("male");
Customer.marshal (New File ("Marshalcust.xml"));
}catch (Exception e) {
E.printstacktrace ();
}
}
}


Example 4 Marshal javaobject

The new Marshalcust.xml generated after the program is executed is as follows:

<?xml version= "1.0" encoding= "UTF-8"?>

<! DOCTYPE Customer SYSTEM "D:\ZEUS\DTD\CUSTOMER.DTD" >
<customer customer_no= "1234566" >
<Name> Li Ming </Name>
<Id_No>210204197910012233</Id_No>
<Sex> male </Sex>
<Birth_Place> Dalian </Birth_Place>
<Birth_Date>1979-10-1</Birth_Date>
<Nationality> China </Nationality>
University of <Education> </Education>
<contact_info id= "0002" >
<Zip_Code>116001</Zip_Code>
<Tel_No>6656456</Tel_No>
</Contact_Info>
</Customer>



The reason and thinking of choosing Zeus:
Java and XML are a pair of born brothers, and when all computer software technology holds up the XML banner, there are 10,000 reasons to achieve the perfect combination of Java and XML. Sun, Apache also provides a powerful XML parsing package, standing on the Shoulders of giants (in fact, Zeus uses Apache xerces to parse XML), Zeus proposes the concept of data binding.

Parsing to binding does not require a complex implementation approach, but provides a simpler and more flexible solution for users. The development of programming technology and the appearance of open software provide a broader space for creativity, choose Zeus, use Zeus, think zeus--no complex technology, only amazing creativity. This may be the meaning of survival in the post-software era, I think.



Related Article

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: info-contact@alibabacloud.com 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.