2005.10.14 株式会社四次元データ 小野彩子
XML DOM XSLT 11章 JAXB(3)
- 11.1. JavaインスタンスよりXML文書を生成する
- 11.2. インスタンスの生成
- 11.3. JAXBコンテキストとMarshaller
11.3 JAXBコンテキストとMarshaller
最後に、XML文書として出力します。XML文書よりインスタンスを作成する場合と同様に、まずJAXBコンテキストを取得します。パッケージ名は、クラスを生成するときに「xjc.sh」コマンドの引数に指定したものです。
JAXBContext jc = JAXBContext.newInstance("test.jaxb");
次に、XML文書を生成する「Marshaller」を作成します。Marshallerは、JAXBContextのcreateMarshallerメソッドを使って作成します。
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT ,
new Boolean(true));
setPropertyでは、出力形式の設定を行っています。例えばここでは、Marshaller.JAXB_FORMATTED_OUTPUTプロパティの値をtrueに設定しています。これにより、出力されたXMLは、要素ごとにインデントされ人間に見やすいものになります。出力は、Marshallerのmarshalメソッドを用いて行います。一つ目の引数は、ルート要素を表すインスタンスです。この例では、employees要素になります。二つ目の引数は、出力先のStreamです。
marshaller.marshal(employees,
new FileOutputStream("employees.xml"));
このプログラムを実行すると、employees.xmファイルに以下のように出力されます。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employees>
<employee>
<name>山田太郎</name>
<nameKana>ヤマダタロウ</nameKana>
<section>開発部</section>
</employee>
<employee>
<name>海野次郎</name>
<nameKana>ウミノジロウ</nameKana>
<section>営業部</section>
</employee>
</employees>
(実習課題1)
9章の実習課題で作成したスキーマやJAXBにより自動生成したクラス(Products、Product...)を使用し、以下のXML文書を生成するプログラムを作成しなさい。
product.xml
<?xml version="1.0"?>
<products>
<product>
<name>ゼロからはじめるJava</name>
<price>1905</price>
</product>
<product>
<name>ゼロからはじめるJ2EE</name>
<price>2095</price>
</product>
</products>

