JAXB の簡単な使い方

前回 (http://www.sbirobo.com/2007/11/jaxb.html) の続きです。

前回は XML に変換したいクラスにアノテーションで印を付けたところまでやりました。こんな感じでしたね。


@XmlRootElement(name = "config")
@XmlType
public class Configuration {
@XmlAttribute(name = "version") public String version;
@XmlElement(name = "server") public Server server;
@XmlElementWrapper(name = "field-def-list")
@XmlElement(name = "field-def") public List fieldDefList;
}

さて使い方ですが、まず jaxb.index ファイルを用意します。アノテーションを付けたクラスのクラス名を列挙したものです。クラスと同じパッケージ階層に置きます。上の例ですと下記のようになります。


Configuration
Server
FieldDef

ではアンマーシャライズ (XML から Java に変換) してみましょう。


// アノテーションを付けたクラスが格納されているパッケージ名を指定
JAXBContext jaxbContext = JAXBContext.newInstance("myapp.config");
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setEventHandler(createValidationEventHandler());
configuration = (Configuration) unmarshaller.unmarshal(
this.getClass().getClassLoader().getResourceAsStream("config.xml"));

ポイントは JAXBContext.newInstance() の引数にパッケージ名を渡すところです。上の jaxb.index を置いたところですね。

以上、細かな説明を省いたところもありますが、あまり考えずにこれだけで XML ファイルから Java インスタンスの生成が実現できます。かんたん! だと思いますがいかがでしょうか。