量産メモ帳

忘れっぽいのでメモを残しています。浅く適当に書きます。

XMLファイルの中身をPOJOのリストに変換する。

スポンサーリンク

XMLファイル名が"pojos.xml"、ルート要素が"PojoRoot"という前提で、以下の様な感じで行ける。


List loadFromXml() throws Exception {
Unmarshaller unmarshaller = JAXBContext.newInstance(AnyNameWillDo.class).createUnmarshaller();
JAXBElement element = (JAXBElement) unmarshaller.unmarshal(new File("pojos.xml"));
Pojo[ ] pojos = (Pojo[ ]) element.getValue();
return Arrays.asList(pojos);
}
@XmlRegistry
class AnyNameWillDo {
@XmlElementDecl(name="Pojos")
JAXBElement thisCanAlsoBeAnyName(Pojo[] value) {
return null;
}
}

ポイントは以下の通り。

  • 任意の名前のクラス(例:AnyNameWillDo)を用意する。
  • このクラスに任意の名前のメソッド(例:thisCanAlsoBeAnyName)を用意する。
    • 引数 … POJO の配列
    • 戻り値 … JAXBElement
    • アノテーション … XmlElementDecl
      • name … XMLファイルのルート要素の名前
  • このクラスを JAXBContext#newInstance メソッドの引数に渡して、Unmarshaller インスタンスを生成する。



ちなみに以下の様にやると、、

Unmarshaller unmarshaller = JAXBContext.newInstance(new Pojo[0].class).createUnmarshaller();

アンマーシャル時に以下の様なエラーメッセージが出力されて失敗する。

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"PojoRoot"). Expected elements are (none)



アンマーシャルやアノテーションの仕組みが分かっていないだけなのかもしれないが、川口さんが書かれた AnyNameWillDo クラスのようなソースコードは全く思い付かなかった。


参考資料: