JDK6.0的新特性之二:使用JAXB2來實現物件與XML之間的對映

okone96發表於2007-01-10

JAXB是Java Architecture for XML Binding的縮寫,可以將一個Java物件轉變成為XML格式,反之亦然。我們把物件與關聯式資料庫之間的對映稱為ORM, 其實也可以把物件與XML之間的對映稱為OXM(Object XML Mapping). 原來JAXB是Java EE的一部分,在JDK6中,SUN將其放到了Java SE中,這也是SUN的一貫做法。JDK6中自帶的這個JAXB版本是2.0, 比起1.0()來,JAXB2()用JDK5的新特性Annotation來標識要作繫結的類和屬性等,這就極大簡化了開發的工作量。實際上,在Java EE 5.0中,EJB和Web Services也透過Annotation來簡化開發工作。另外,JAXB2在底層是用StAX()來處理XML文件。 閒話不多說了,下面用程式碼演示在JDK6中如何來用JAXB2

public class JAXB2Tester {
public static void main(String[] args) throws JAXBException,IOException {
JAXBContext context = JAXBContext.newInstance(Person.class);
//下面程式碼演示將物件轉變為xml
Marshaller m = context.createMarshaller();
Address address = new Address("China","Beijing","Beijing","ShangDi West","100080");
Person p = new Person(Calendar.getInstance(),"JAXB2",address,Gender.MALE,"SW");
FileWriter fw = new FileWriter("person.xml");
m.marshal(p,fw);

//下面程式碼演示將上面生成的xml轉換為物件
FileReader fr = new FileReader("person.xml");
Unmarshaller um = context.createUnmarshaller();
Person p2 = (Person)um.unmarshal(fr);
System.out.println("Country:"+p2.getAddress().getCountry());
}
}

@XmlRootElement//表示person是一個根元素
class Person {
@XmlElement
Calendar birthDay; //birthday將作為person的子元素

@XmlAttribute
String name; //name將作為person的的一個屬性

public Address getAddress() {
return address;
}

@XmlElement
Address address; //address將作為person的子元素

@XmlElement
Gender gender; //gender將作為person的子元素

@XmlElement
String job; //job將作為person的子元素

public Person(){
}

public Person(Calendar birthDay, String name, Address address, Gender gender, String job) {
this.birthDay = birthDay;
this.name = name;
this.address = address;
this.gender = gender;
this.job = job;
}
}

enum Gender{
MALE(true),
FEMALE (false);
private boolean value;
Gender(boolean _value){
value = _value;
}
}

class Address {
@XmlAttribute
String country;
@XmlElement
String state;
@XmlElement
String city;
@XmlElement
String street;
String zipcode; //由於沒有新增@XmlElement,所以該元素不會出現在輸出的xml中

public Address() {
}

public Address(String country, String state, String city, String street, String zipcode) {
this.country = country;
this.state = state;
this.city = city;
this.street = street;
this.zipcode = zipcode;
}


public String getCountry() {
return country;
}
}

執行該程式,我們會得到一個person.xml的檔案,如下:

xml version="1.0" encoding="UTF-8" standalone="yes" ?>

<person name="JAXB2">
<birthDay>2006-12-28T08:49:27.203+00:00birthDay>
<address country="China">
<state>Beijingstate>
<city>Beijingcity>
<street>ShangDi Weststreet>
address>
<gender>MALEgender>
<job>SWjob>
person>

控制檯會輸出

Country:China

最後,想說一點,除了JAXB之外,我們還可以透過XMLBeans和Castor等來實現同樣的功能。

[@more@]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/750220/viewspace-889296/,如需轉載,請註明出處,否則將追究法律責任。

相關文章