JAXB Hello Worldの例
JAXBは、Java Architecture for XML Bindingを表し、JAXBアノテーションを使用してJavaオブジェクトをXMLファイルとの間で変換します。 このチュートリアルでは、JAXBを使用して次のことを行う方法を示します。
-
マーシャリング– JavaオブジェクトをXMLファイルに変換します。
-
非整列化-XMLコンテンツをJavaオブジェクトに変換します。
この記事で使用されている技術
-
JDK 1.6
-
JAXB 2.0
JAXBの操作は簡単です。オブジェクトにJAXB注釈を付け、後でjaxbMarshaller.marshal()またはjaxbMarshaller.unmarshal()を使用してオブジェクト/ XML変換を実行します。
1. JAXBの依存関係
JDK1.6以降を使用している場合は、JAXB is bundled in JDK 1.6であるため、追加のjaxbライブラリは必要ありません。
注
JDK <1.6の場合、hereからJAXBをダウンロードし、プロジェクトのクラスパスに「jaxb-api.jar」と「jaxb-impl.jar」を配置します。
2. JAXBアノテーション
XMLファイルとの間で変換する必要があるオブジェクトの場合、JAXBアノテーションを付ける必要があります。 注釈はかなり自明です。詳細な説明については、このJAXB guideを参照できます。
package com.example.core;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
}
3. オブジェクトをXMLに変換
JAXBマーシャリングの例では、顧客オブジェクトをXMLファイルに変換します。 jaxbMarshaller.marshal()には、オーバーロードされたメソッドが多数含まれています。出力に適したメソッドを見つけてください。
package com.example.core;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBExample {
public static void main(String[] args) {
Customer customer = new Customer();
customer.setId(100);
customer.setName("example");
customer.setAge(29);
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
出力
29 example
4. XMLをオブジェクトに変換
JAXBアンマーシャリングの例では、XMLファイルのコンテンツを顧客オブジェクトに変換します。 jaxbMarshaller.unmarshal()には、オーバーロードされたメソッドがたくさん含まれています。自分に合ったメソッドを見つけてください。
package com.example.core;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class JAXBExample {
public static void main(String[] args) {
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
出力
Customer [name=example, age=29, id=100]