How to Use Zeus to bind XML-Java data

Source: Internet
Author: User
How to Use Zeus to bind XML-Java data
Author: Zhong jiahao Source: http://www.cjsdn.net
Zeus can bind Java objects to XML files to facilitate the application of data in J2EE. This article describes how to compile and use Zeus. The DTD and XML files used during the binding process are also described. 1. Introduction to Zeus enhydra is the name of a non-profit organization named after an otter who grew up at the seaside of California. Unlike the famous Apache, enhydra is committed to researching the e-commerce solution of application server. Zeus is one of the many tools and software developed by enhydra. Its function is to bind javaobject and XML data. It can convert arbitrary XML files into corresponding javaobject files, and convert data between these two forms conveniently. The latest version of Zeus is zeus1.0 beta 3.5. Because it is fully open in source code, you can download the source code at http://zeus.enhydra.org/software/downloads/index.html. 2. Prerequisites 2.1 using XML as the data carrier XML (Extensible Markup Language) was developed by W3C and supported by almost all major companies in the world. XML is a very flexible text format. Compared with HTML, XML continues its simple and easy-to-understand syntax, but it has more flexibility and scalability. Example 1 is an XML file describing customer information. As the language for describing data, XML is organized freely and clearly. <? XML version = "1.0" encoding = "GBK"?>
<Customer customer_no = "00001">
<Name> Li Jun </Name>
<Id_no> 210106421016001 </id_no>
<Sex> male </sex>
<Birth_place> Dalian </birth_place>
<Birth_date> 1942-10-16 </birth_date>
<Nationality> China </nationality>
<Education> high school </education>
<Address> shahekou, Dalian </address>
<Contact_info id = "00001" type = "parmname" text = "parmname">
<Zip_code> 116001 </zip_code>
<Tel_no> 2645677 </tel_no>
</Contact_info>
</Customer>
Example 1: the XML file describing customer has a clear structure: it describes a "customer" entity, which has its attributes: name, ID number, gender, place of birth, birthday, place of birth, contact information (ZIP code, phone number), etc. The first line indicates that the XML file version is 1.0 and uses the "GBK" encoding method (if you want to parse Chinese, GBK or gb2312 is required ). And yes. In <contact>, you can continue to include sub-tags :,. The XML language of the User-Defined tag gives users sufficient freedom to represent data, but it also makes it difficult to display and parse. To solve this problem, w3C restricts XML in terms of format control and tag definition. For example, it is a pair of unqualified tags. 2.2 document type definition (DTD) is used to define the relationship between elements in an XML document. A dtd can exist in a file with the XML applied to it, or it can be a file separately. 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: The DTD file does not have a regular Square. The DTD file in example 2 defines the customer element described in XML in Example 1, the tags in XML are given meaning, and the relationship between customer and other elements is well explained. The existence of the DTD file makes the data in XML in a prescribed form. The two are closely connected and easily reminiscent of another important data organization method-fields and data in the database table. DTD-XML, a structure similar to the table structure-data class, provides a natural convenience for the mutual conversion of the two technologies. By using DTD, the data in the table can be conveniently expressed in XML. 3. compile your Zeus file. The downloaded Zeus file is a zip file. If you select Source Code download, you must compile it before using it. This article introduces the use of Zeus, starting with source code compilation. The compilation method is described in detail in the downloaded docs folder. As part of the Java technology camp, Zeus uses other outstanding Java tools while fully contributing to its own efforts. For example, Apache ant is used for compiling. You can find the ant. jar file under Zeus/lib. The only thing to do before compilation is to set the java_home environment variable of the operating system. For example, in windows, if JDK is installed in D:/jdk1.3.1, run set java_home = D:/jdk1.3.1. After preparation, you can start to compile Zeus. Ant is an easy-to-use compilation tool. The build. xml file can be used to set all compilation details and file assembly. The Zeus compilation file is located in build. xml under the root directory. This XML file contains all the details of compiling and assembling the Zeus. jar file with high readability. Run the command in the root directory of Zeus. /bin/build. bat targets, ant can find build in the current directory. XML file. If no parameter is input, ant will output a prompt asking you to input and compile all source code of targets: compile: Compile Zeus, and place it under build/classes; bin: copy the files in the original src/bin directory to build/bin, copy the jar files in the original lib directory to build/lib, and copy the combined Zeus. jar is placed in this folder; Doc: Compile Javadoc and copy the result to bin/docs/apidoc. Sample and test are used to compile routine and Test Code respectively. If you do not want to compile the program step by step, set the targers parameter to all, so that ant will automatically compile all targets in the correct order. After compilation, a build folder will appear, where all the compiled files are located. Check the build/bin folder. The Zeus. jar file that appears is the compiled tool. If you have enough experience modifying the source code and build. xml file of Zeus, you can create your own Zeus. 4. The first step to generate a Java object that describes XML is to use Zeus to automatically generate Java source code. Run Zeus. BAT in build/bin/with the following syntax: Zeus. Bat-constraints =
[-Outputdir =]
[-Collapsesimpleelements =]
[-Ignoreidattributes =]
[-Javapackage =]
[-Root =]
Bind the XML file in Example 1 to Java objects. The first step is to generate a Java file. The specific solution is to use Zeus. org. enhydra. zeus. util. dtdsourcegenerator, customer in example 2. the DTD file is a required constrains parameter. First, run the following command: place the customer file under the C:/Zeus/DTD file, create a C:/Zeus/zjhsample, and run the following command: C:/Zeus>. /build/bin/Zeus. bat
-Constraints = DTD/customer. DTD
-Outputdir = zjhsample-javapackage
= Com. Zest. zeustest. Binding
-Collapsesimpleelements = true
View C:/Zeus/zjhsample/COM/zw/
Zeustest/binding folder,
Six files are generated:
Customer. Java, customerimpl. Java,
Contact_info.java, contact_infoimpl.java,
Customerunmarshaller. Java,
Unmarshallable. java.
The generated class names can follow the rules: customer and contact_info are the names of non-simple elements in the DTD file, and Zeus generates interfaces with the same name; customerimpl and contact_infoimpl are the classes that implement these interfaces. Customerunmarshaller and unmarshallable seem a bit strange, but they do not come out of thin air: The unmarshallable interface inherits from Org. XML. sax. contenthandler provides an interface for parsing XML legitimacy. All elementimpl classes must inherit this interface. customerunjavasaller provides an interface for anti-decoding XML, inputting XML files and Returning Customer objects. All the secrets of Data Binding are hidden in these files and can be edited using any text editor. But as stated in the program declaration, modifying these programs may cause data binding failure. Finally, compile these six java files: javac *. Java to generate the class file. In this way, the Java class used to describe the XML file is obtained. 5. Conversion of Marshal and unmarshal -- conversion of XML and Java objects common XML files are suitable for data transmission between different technical platforms. Java objects can provide more convenient interfaces for Java programs, the Java object generated using the Zeus tool is like a bridge that closely links the two (see figure 1 ). It not only builds enough internal properties to describe the values of each element in the XML file, but also provides interfaces that can convert Java objects to XML files: unmarshal and marshal. Unmarshal: decode the XML file as javaobject; decodes the javaobject as an XML file.
Figure 1: Conversion of Java objects and XML files 5.1 unmarshal XML files to Java objects once the Java objects generated by Zeus are compiled, converting an XML file into a Java expression is a simple and pleasant task. This process is described as "undecoded Al", which is actually the unmarshal () method of the elementimp object generated by Zeus Based on the DTD file. Like the automatic manufacturing machine of items in sci-fi novels, the unmarshal method is used to input XML files packaged in the form of Java file, writer, or inputstream. One click on the unmarshal button, the Java representation of XML data was born easily. The merunmarshal class in the example Program (Example 3) completes the customerinfo. xml job in unmarshal Example 1 and outputs the result to the screen. Package com. zjh. zeustest;
Import java. Io .*;
Import com. zw.zeustest. Binding. *; public class customerinfo
{
Public static void
Main (string [] ARGs)
{
If (ARGs. length! = 1)
{
System. Out. println
("Please in put the location of XML file ");
Return;
}
Try {
Customer customer =
Customerunmarshaller. unmarshal
(New file (ARGs [0]), false );
System. Out. println
("Name:" + customer. getname ());
System. Out. println
("Credential number:" + customer. getid_no ());
System. Out. println
("Gender:" + 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 compile the program and run the following command: Java-classpath./; ../lib/xerces. Jar
Com. zw.zeustest. Customer unmarshal
../Cust. xml
Enter the following name: Li Jun
ID number: 210106421016001
Gender: male
Birthplace: Dalian
Nationality: Chinese
Education level: High School
Zip code: 116001
Phone number: 2645677
5.2 It is the inverse process of unmarshal to convert the data from the Java object form to the XML file from the marshal Java object to the XML file. In semantics, the term Marshal (Decoding) is also used. The following example (Example 4) provides a complete example of data binding: Read Cust. xml
Unmarshal XML
Modify the attribute value of a Java object
Marshal Java object package com. zw.zeustest;
Import java. Io .*;
Import com. zw.zeustest. Binding. *; public class customermarshal
{Public static void
Main (string [] ARGs)
{
If (ARGs. length! = 1)
{
System. Out. println
("Please in put the 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 (" ");
Customer. setid_no ("210204197910012233 ");
Customer. setname ("Li Ming ");
Customer. setnationality ("China ");
Customer. setsex ("male ");
Customer. Marshal (New
File ("externalcust. 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>
<Education> university </education>
<Contact_info id = "0002" type = "parmname" text = "parmname">
<Zip_code> 116001 </zip_code>
<Tel_no> 6656456 </tel_no>
</Contact_info>
</Customer>
Reason and consideration for choosing Zeus: Java and XML are a natural brother. When all computer software technologies hold high the XML flag, there are 10 thousand reasons for the perfect combination of Java and XML. Sun and Apache also provide powerful XML parsing packages, standing on the shoulders of giants (in fact, Zeus uses Apache xerces to parse XML). Zeus proposes the concept of data binding. It does not require complicated implementation methods from parsing to binding, but provides users with simpler and more flexible solutions. The development of programming technology and the emergence of open software provide a broader space for creativity. The choice of Zeus, the use of Zeus, and the consideration of Zeus-no complex technology, only amazing creativity. This may be the true meaning of program survival in the Post-software age, I think.

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.