Use JAXB to process XML documents - Sneak peek

zhaozj2021-02-11  206

Jaxb may cause your interest in JAXB. You may not know what JAXB is, I want to know what the benefits it, if this is what you need, you will take time to study it, or you only need to use the most basic function. However, Sun About JAXB's document is 80 pages. I think most people have no patience to read this long story. This article introduces the basic use of JAXB with a short space, and it is sneak peek. The code included in this article includes the JAXB1.0 Early Access version and the code used in this article. Welcome to discuss with me: Mailto: Boyofjava@sina.com

This article assumes that you will use Java programming, understand and understand XML, DTD.

1 Why use JAXB

The general methods for processing XML data in Java have SAX, DOM, etc. Among them, SAX uses very troublesome and cannot modify XML data; and DOM's handling big document is very slow, and ease of use does not have to go. Where is SAX? In fact, whether it is SAX or DOM is not prepared for Java, they are all unified underlying interfaces of XML documents, independent of language.

Now we have another choice. This is JAXB and JDOM. Jdom has nothing to do with this article. The latest version is beta8. If you are interested, you can visit http://www.jdom.org/.

The full name of JAXB is JavaTM Architecture for XML Binding. It is currently a 1.0 Early Access version, and only registered as members can be downloaded in Sun's Java site. JAXB features that map you use DTD to the XML document to Java objects, provide simple, fast data operation mode. To access the elements in XML, attributes as long as they pass a series of Getter and Setter methods on the appropriate object. You can also write object's data into the XML file through the Marshal method, read the data of the XML file into the object through the UNMARSHAL method, verify that the XML file is constrained by the XML file through the Validate method. The disadvantage of JAXB is that only access to specific (that is, you use DTD definition) XML documents.

2 JAXB work

JAXB includes a run class library and a model compiler. First you have to define the XML DTD and write a binding schema. DTD defines the XML document, the binding mode is also an XML file, indicating how the XML document defined by DTD is mapped to Java objects. Run the compiler, pass the DTD and binding mode as a parameter to the compiler, and the compiler generates Java code. Compile the generated Java code, you can access the XML document through these code.

3 JAXB installation

Take 1.0 Early Access as an example, it is not included in the JDK, first go to http://java.sun.com/xml. Note Because it is an earlier version, you need to log in to download. The source code included in this article contains JAXB1.0 Early Access. After downloading, decompress the file, there are two files in the lib directory. JAXB-RT-1.0-Ea.jar is a running support library, JAXB-XJC-1.0-Ea.jar is a mode compiler. Note that the XJC file in the bin directory can only be used under UNIX. If your system is Windows, then you need to manually enter the command to compile in the command line window. In order to run the mode compiler and the code it generated anywhere, we have to join the two files to the classpath. A simple way is to copy these two files to jRE / lib / ext.

4 a simple example

There is such an XML document. It describes the list of books, for example:

File EXAMPLEA.XML

Java programming

Zhang 3

2002-6-6

35.0

XML in Java

Li 4

2002-9-16

92.0

Its DTD file is as follows:

File BookList.dtd

Now let's write a simplest binding mode, and its file extension should be xjs.

File BookList.xJS

Now you can run the mode compiler to generate Java code, first ensure that the ClassPath contains two JAR files in JAXB. Windows users Note that the file in the bin directory is useless. Run on the command line:

Java com.sun.tools.xjc.main booklist.dtd booklist.xjs

If there is no problem, the compiler generates two files of book.java, booklist.java. You don't have to understand the code in these two source files, just know how to use the methods they provide. Their inheritance structure is like this:

Java.lang.object

Javax.xml.bind.validatableObject

Javax.xml.bind.marshallableObject

Javax.xml.bind.marshallableroTelement

Booklist or book

BookList.java mainly includes the following methods

BookList () // Constructor

List getBook () // Get a collection of books, the actual type of objects in List is Book, you can add, modify, delete the elements

Void deleteBook () // Delete collection

Void EmptyBook () // Delete and generate a new empty collection

Void Marshal (x) // Write the data into the XML document

Void unmarshal (x) // reads data from an XML document into an object

Void validate (x) // checks if the DTD constraint is compliant, and the subtree is checked. In this example is the Book Collection of Booklist

Void validatethis () // Checks if the DTD constraint is compliant, and does not check the sub-tree where Marshal, Unmarshal, Validate is overloaded, with a variety of parameters (you can refer to the JAXB API document).

Book.java mainly includes the following methods

BOOK ()

String getName ()

String getAuthor ()

String getpublishdate ()

String getprice ()

Void setName (String X)

Void setauthor (String X)

Void setPublishDate (String X)

Void setprice (String X)

Void Marshal ()

Void unmarshal ()

void validate ()

Now we can use these two files to access XML. First compile these two files. Write a Test.java file, put it and the two files generated together, and the front of Examplea.xml. This program reads data from Examplea.xml to modify (turn the first book author to Wang 5), write Exampleb.xml. Because Chinese coding problems, we need more procedures.

Document test.java

Import java.io. *;

Import java.util. *;

Import javax.xml.bind. *;

Import javax.xml.marshal. *;

Public class test {

Public static void main (string [] args) throws exception {

BookList BL = New BookList ();

FileInputStream Fis = New FileInputStream ("eXamplea.xml");

Try {

BL = BL.unmarshal (FIS);

} finally {

fis.close ();

}

List books = bl.getbook ();

Book b = (book) books.get (0);

B.SetAuthor ("Wang 5");

Bl.Validate (); // First verified, otherwise Marshal will be wrong

FileOutputStream Fos = New FileOutputStream ("EXAMPLEB.XML");

XMLWRITER XW = New XMLWRITER (FOS, "GBK");

Try {

BL.Marshal (XW);

} finally {

Fos.close ();

}

}

}

Compile operation, generated files exampleb.xml as follows:

Java programming

Wang 5

2002-6-6

35.0

XML in Java

Li 4

2002-9-16

92.0 5 Further: Data Type Conversion

You may have noticed that in the above example, the getprice method of the generated book object returns String, in fact it should be float. The same PublishDate is at the date type, not a string. This is because our binding mode is written too simple, the mode compiler generates the default String type. Now let's write this:

File BookList2.xJS

PARSE = "transdate.parsedate" print = "transdate.printdate" />

Run the compiler with java com.sun.tools.xjc.main booklist.dtd booklist2.xjs. The corresponding code of the generated book file is:

Float getprice ()

Java.util.date getPublishDate ()

Booklist2.xjs line 3 converts the price into a float type, the float type is a simple type, so it is possible to describe with the convert = "float". PublishDate needs to turn into java.util.date, which is a class, and he does not have a string as a constructor of parameters. PARSE = "transdate.parsedate" means the transdate.parsedate () method when using UNMARSHAL read data. This static method returns java.util.date with a string as a parameter. The role of Print = "Transdate.printDate" is reversed. TRANSDATE This class requires us.

Document Transdate.java

Import java.util.date;

Public class transdate {

Private static java.text.SIMPLEDATEFORMAT DF

= New java.text.SIMPLEDATEFORMAT ("YYYY-MM-DD");

Public Static Date Parsedate (String D) {

Try {

Return DF.PARSE (D);

} catch (java.text.parseexception pe) {

System.out.print (PE);

Return new Date ();

}

}

Public Static String PrintDate (DATE D) {

Return DF.FORMAT (D);

}

}

6 The examples that make JAXB can do, but this example does not mention this paper is simple. In fact, JAXB can also define which elements (attributes) of the document can be converted into classes, which are converted to the class. Properties. Handling the properties of the elements. Handle the enumeration value. Generate an interface for some elements (because JAXB does not support Namespace), define inheritance structures, and the like.

7 JAXB can't do it

The sun documentation mentioned:

Supports only DTD definitions XML

Namespace

No internal subset, Notations, Entity, Entities, etc.

Also, I found that if you want to write a handling instruction to the XML document, such as specifying the conversion style sheet

It doesn't seem to do it in JAXB. There is a Chars (String Str) method in javax.xml.marshal.xmlwriter, you can put strings to the XML file declaration, but this method is escaped to special characters, that is There is no way to do it. This is very strange, because this is a common function, it is not difficult to achieve. Maybe there may be a way I have not found. There is a DOCTYPE method to write a DOCTYPE statement.

8 Reference documentation

1 THE JAVATM Architecture for XML Binding User's Guide

(http://java.sun.com/xml/jaxb/jaxb-docs.pdf)

2 Web Services Made Easier. The Java TM Apis and Architectures for XML, a Technical White Paper (http://java.sun.com/xml/webservices.pdf)

转载请注明原文地址:https://www.9cbs.com/read-5154.html

New Post(0)