JavaEE学習のJAXB

8746 ワード

はじめに
JAXB——Java Architecture for XML Bindingは、XML SchemaによってJava類を生成できる技術です。JAXBは、XMLのインスタンスドキュメントを逆にJavaオブジェクトツリーを生成する方法を提供し、Javaオブジェクトツリーの内容をXMLのインスタンスドキュメントに書き換えることもできます。
 
二、JAXB関連のクラスとインターフェース
(1)JAXBCN text。  JAXBCN text類はJAXB APIのクライアントの入り口に提供されます。JAXBバインディングフレームワークを実現するために必要なXML/Javaバインディング情報を管理する抽象的なものを提供しています。これらの操作には、ソリューション、編成、検証(Validator)が含まれています。通常はJAXBContext.newInstance(XXX.class)を使ってJAXBCN textのインスタンスを取得します。(Studentは私が定義したEntityです。)
JAXBContext ctx = JAXBContext.newInstance(Student.class)
(2)ユニバーサル・シャーラー。ユニマルシェは、XMLデータを新たに作成されたJavaコンテンツツリーに逆順序で並べ替えるプロセスを管理するInterfaceであり、ソリューション時にXMLデータを選択的に検証することができます。File,InputStream,URL,StringBufferなど,さまざまな種類の入力に対して,様々な重負荷unmasharl方法を提供しています。unmashel方法はnullに戻らないです。もしunmashelがXMLの内容のルートをJAXBのマッピング対象にセットできないなら、JAXBExceptionをスローします。
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Student stu = (Student) unmarshaller.unmarshal(file);
(3)マルシェラーです。Marshallerは、クライアント・アプリケーションにJavaコンテンツツリーをXMLデータに変換することができるようにする。それは様々な重さのマルシェ方法を提供します。デフォルトでは、XMLデータをjava.io.OutputStreamまたはjava.io.Writerに生成する場合、MarshlerはUTF-8を使用して符号化されます。
			Marshaller marshaller = ctx.createMarshaller();			
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);//      
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");//       ,   UTF-8		
			marshaller.marshal(stu, xmlFile);
 
三、JAXB関連Annotation
(1)@Xml RootElementは、Java類または列挙タイプをXML要素にマッピングする。
(2)@XmlElementは、Java類の属性を属性と同名のXML要素にマッピングします。
(3)@Xml Attributeは、Java類の属性を属性と同名のXML属性にマッピングします。
 注意事項:
(1)プログレッシブ(masharl)をXMLとするJava類については、メンバー変数をpublicとして宣言してはいけません。さもなければ、運行は異常です。
comple.sun.xml.internal.bind.v.2.runtime.Illegel Annotations Exception
(2)コメントは直接メンバー変数に置くことができません。メンバー変数のgetterまたはsetter方法に置くことができます。いずれかを選択してください。そうでないと、IllaガルAnnotations Exceptionの異常も投げられます。
 
四、例
(1)一つのStudentクラスを定義する
package cn.com.infosky.Jaxb;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;


@XmlRootElement(name="Root")
public class Student implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8317239764136972094L;

	private String name;

	private String country;
	
	private String birthDate;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the country
	 */
	public String getCountry() {
		return country;
	}

	/**
	 * @param country
	 *            the country to set
	 */
	public void setCountry(String country) {
		this.country = country;
	}

	/**
	 * @return the birthDate
	 */
	public String getBirthDate() {
		return birthDate;
	}

	/**
	 * @param birthDate the birthDate to set
	 */
	public void setBirthDate(String birthDate) {
		this.birthDate = birthDate;
	}
}
 
(2)StudentオブジェクトをMashlerインターフェースを介してTestJaxb.xmlファイルにプログレッシブ化する
	public void Obj2Xml()  {
		File xmlFile = new File("C:/TestJaxb.xml");
		JAXBContext ctx;
		try {

			ctx = JAXBContext.newInstance(Student.class);
			
			Marshaller marshaller = ctx.createMarshaller();			
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);//      
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");//       ,   UTF-8
			
			Student stu = new Student();
			stu.setName("Zhangsan");
			stu.setCountry("CN");
			
			//      
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			stu.setBirthDate(sdf.format(new Date()));			
			marshaller.marshal(stu, xmlFile);
			System.out.println("Obj2Xml Over!");

		} catch (JAXBException e) {
			System.out.println("error");

			System.out.println(e.toString());
			System.out.println(e.getStackTrace());
			// TODO: handle exception
		}
	}
 
運転後に生成されるTestJaxb.xml構造:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Root xmlns="http://www.example.org/wzhang">
    <birthDate>2014-04-10</birthDate>
    <country>CN</country>
    <name>Zhangsan</name>
</Root>
 
(3)ユニバーサル・シャーラーインターフェースでXMLファイルからStudentオブジェクトを取得する
	public void XmlToObj() {

		try {

			File file = new File("C:\\TestJaxb.xml");
			JAXBContext jaxbContext = JAXBContext.newInstance(Student.class);

			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			Student stu = (Student) unmarshaller.unmarshal(file);
			System.out.println(stu.getName()+"..."+stu.getBirthDate());

		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
 
(4)テストコード
	public static void main(String[] args) {
		new App().Obj2Xml();
		//new App().XmlToObj();
	}
 
ソースコードの例のダウンロード