如果找到了对您有用的资料,烦请点击右手边的Google广告支持我继续共享知识,谢谢! http://dengpeng.spaces.live.com/

2008年7月17日星期四

Simple JAXB Application

Java Architecture for XML Binding (JAXB) allows Java developers to map Java classes to XML representations. JAXB provides two main features: the ability to marshal Java objects into XML and the inverse, i.e. to unmarshal XML back into Java objects. In other words, JAXB allows storing and retrieving data in memory in any XML format, without the need to implement a specific set of XML loading and saving routines for the program's class structure.

JAXB is particularly useful when the specification is complex and changing. In such a case, regularly changing the XML Schema definitions to keep them synchronised with the Java definitions can be time consuming and error prone.

The tool "xjc" can be used to convert XML Schema and other schema file types (as of Java 1.6, RELAX NG and XML DTDs are supported experimentally) to class representations. Classes are marked up using annotations from javax.xml.bind.annotation.* namespace, for example, @XmlRootElement and @XmlElement. XML list sequences are represented by attributes of type java.util.List. Marshallers and Unmarshallers are created through an instance of JAXBContext.

In addition, JAXB includes a "schemagen" tool which can essentially perform the inverse of "xjc", creating an XML Schema from a set of annotated classes.

--http://en.wikipedia.org/wiki/JAXB

country.xsd

<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="country" type="Country"/>
<xs:complexType name="Country">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="population" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:schema>





country.xml


<country
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="country.xsd">
<name>France</name>
<population>60144000</population>
</country>





1. Download JAXB from https://jaxb.dev.java.net/


2. Convert XML schema to Java class source file. The command is xjc.bat -package.name sourceXMLSchema.xsd. For example, execute xjc.bat –countries country.xsd, we should get these files:



  • Country.java


  • ObjectFactory.java



3. Create a project in Netbeans, and copy the generated source files to the folder of project source. And do not forget to add the JAXB 2.1 library in project properties.


4. Here below is the source code of main java which shows both read and write XML functions:


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package simplejaxb;

import countries.Country;
import countries.ObjectFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
*
* @author pdeng
*/

public class Main {

/**
* @param args the command line arguments
*/

public static void main(String[] args) {
// Read and convert a XML file from disk to a Java object in memory
readAndConvert("country.xml");

// Write a Java object in memory to a XML file on disk
writeXML("country2.xml");
}

private static void readAndConvert(String path) {
try {
// Read XML to Java object
JAXBContext jc = JAXBContext.newInstance("countries");
Unmarshaller um = jc.createUnmarshaller();
JAXBElement<Country> countryElement = (JAXBElement<Country>) um.unmarshal(new File(path));
Country c = countryElement.getValue();

//Print out values from Java object
System.out.println(c.getName());
System.out.println(c.getPopulation());
} catch (JAXBException ex) {
ex.printStackTrace();
}
}

private static void writeXML(String path) {
try {
// Create java object and assign values to this object
JAXBContext jaxbContext = JAXBContext.newInstance("countries");
ObjectFactory objFactory = new ObjectFactory();
Country c = objFactory.createCountry();
c.setName("China");
c.setPopulation(BigDecimal.valueOf(130000000));
JAXBElement<Country> countryElement = objFactory.createCountry(c);

// Create instance of marshaller and write object to XML file
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
marshaller.marshal(countryElement, new FileOutputStream(path));
} catch (Exception ex) {
ex.printStackTrace();
}

}
}


5. if you still confuse about how the app works, you can douload the project archieve from http://www.mediafire.com/?zpt74jm5gs2








This is another example which is a bit complex than the one above. We have XML Schema file and a XML file.



books.xsd



<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" jaxb:version="1.0">


<xs:element name="Collection">
<xs:complexType>
<xs:sequence>
<xs:element name ="books">
<xs:complexType>
<xs:sequence>
<xs:element name="book" type="bookType" minOccurs="1" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:complexType name="bookType">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="ISBN" type="xs:long"/>
<xs:element name="price" type="xs:string"/>
<xs:element name="authors" >
<xs:complexType>
<xs:sequence>
<xs:element name="authorName" type="xs:string" minOccurs="1"
maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="description" type="xs:string" minOccurs="0"/>
<xs:element name="promotion">
<xs:complexType>
<xs:choice>
<xs:element name="Discount" type="xs:string" />
<xs:element name="None" type="xs:string"/>
</xs:choice>
</xs:complexType>
</xs:element>
<xs:element name="publicationDate" type="xs:date"/>
<xs:element name="bookCategory">
<xs:simpleType>
<xs:restriction base="xs:NCName">
<xs:enumeration value="magazine" />
<xs:enumeration value="novel" />
<xs:enumeration value="fiction" />
<xs:enumeration value="other" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
<xs:attribute name="itemId" type="xs:string" />
</xs:complexType>



<xs:simpleType name="bookCategoryType" >
<xs:restriction base="xs:string">
<xs:enumeration value="magazine" />
<xs:enumeration value="novel" />
<xs:enumeration value="fiction" />
<xs:enumeration value="other" />
</xs:restriction>
</xs:simpleType>


</xs:schema>





books.xml



<?xml version="1.0"?>
<Collection>
<books>
<book itemId="999">
<name>
Learning JAXB
</name>
<ISBN>
123445
</ISBN>
<price>
34 $
</price>
<authors>
<authorName> Jane Doe
</authorName>
</authors>
<description>
This books contains step by step instructions for beginners so that they can start using Java API for XML Binding.
</description>
<promotion>
<Discount> 10% on this book if purchased by March 2003
</Discount>
</promotion>
<publicationDate>
2003-01-01
</publicationDate>
<bookCategory>other
</bookCategory>
</book>

<book itemId="129">
<name>
Java Webservices today and Beyond
</name>
<ISBN>
522965
</ISBN>
<price>
29 $
</price>
<authors>
<authorName> John Brown
</authorName>
<authorName> Peter T.
</authorName>
</authors>
<description>
This books contains information for users so that they can start using Java Web Services Developer Pack.
</description>
<promotion>
<Discount> Buy one get Learning webservices Part 1 free
</Discount>
</promotion>
<publicationDate>
2002-11-01
</publicationDate>
<bookCategory>magazine
</bookCategory>
</book>
</books>
</Collection>




Follow the same first three steps of previous example. Here below is the source of main.java to read and output a XML file:



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package hellojaxb;

import books.BookType;
import books.Collection;
import books.Collection.Books;
import books.ObjectFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
*
* @author pdeng
*/

public class Main {

/**
* @param args the command line arguments
*/

public static void main(String[] args) {
// Read and convert a XML file from disk to a Java object in memory
readAndConvert("books.xml");

// Write a Java object in memory to a XML file on disk
writeXML("jaxbOutput2.xml");
}

private static void readAndConvert(String path) {
try {
// Read XML to Java object
JAXBContext jc = JAXBContext.newInstance("books");
Unmarshaller um = jc.createUnmarshaller();
Collection col = (Collection) um.unmarshal(new File(path));
Books bt = col.getBooks();
List bl = bt.getBook();

//Print out values from Java object
BookType book = (BookType) bl.get(0);
System.out.println(book.getName());
} catch (JAXBException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}

private static void writeXML(String path) {
try {
// Create java object and assign values to this object
JAXBContext jaxbContext = JAXBContext.newInstance("books");
ObjectFactory objFactory = new ObjectFactory();
Collection collection = (Collection) objFactory.createCollection();
Books booksType = objFactory.createCollectionBooks();
List bookList = booksType.getBook();

// Create one instance of book
BookType book = objFactory.createBookType();
book.setItemId("307");
book.setName("JAXB today and beyond");
book.setDescription("This is an intermediate book on JAXB");
book.setISBN(987665L);
book.setPrice("45$");
//book.setPublicationDate();
book.setBookCategory("other");
BookType.Promotion promotionType = objFactory.createBookTypePromotion();
promotionType.setDiscount("5% off regular price");
book.setPromotion(promotionType);
BookType.Authors authorsType = objFactory.createBookTypeAuthors();
List authorList = authorsType.getAuthorName();
authorList.add("Richard K");
book.setAuthors(authorsType);

bookList.add(book);
collection.setBooks(booksType);

// Create instance of marshaller and write object to XML file
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
marshaller.marshal(collection, new FileOutputStream(path));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}


5. if you still confuse about how the app works, you can douload the project archieve from http://www.mediafire.com/?vm5gy2xrcjd

没有评论: