9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JAXBを使ってみました

Posted at

JAXBを使ってみたのでメモしておきます。

はじめに

JAXB(Java Architecture for XML Binding)とは、Java SE 1.6 以降に含まれるライブラリで、Javaのオブジェクトと、XMLを、相互に変換することができます。

似たようなライブラリには、ApacheのXMLBeansがあるようですね。

オブジェクト→XML変換

こんな感じで、さくっとできちゃいました。

変換元データを保持するクラス
public class PersonBean {

    // Getter/Setterを省略して、publicにしてあります。

    public String name;
    public int age;

}
変換処理
    @Test
    public void testMarshal() {
        // 準備

        // 入力オブジェクト
        PersonBean personBean = new PersonBean();
        personBean.name = "山田 太郎";
        personBean.age = 20;

        // 期待値
        String expected = "" //
                + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" //
                + "<personBean>\n" //
                + "    <name>山田 太郎</name>\n" //
                + "    <age>20</age>\n" //
                + "</personBean>\n" //
        ;

        // 出力先
        StringWriter sw = new StringWriter();

        // 実行
        JAXB.marshal(personBean, sw);

        // 検証
        assertThat(sw.toString(), is(expected));
    }

XML→オブジェクト変換

変換処理
    @Test
    public void testUnmarshal() {
        // 準備

        // 入力XML
        String input = "" //
                + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" //
                + "<personBean>\n" //
                + "    <name>山田 太郎</name>\n" //
                + "    <age>20</age>\n" //
                + "</personBean>\n" //
        ;
        StringReader sr = new StringReader(input);

        // 実行
        PersonBean actual = JAXB.unmarshal(sr, PersonBean.class);

        // 検証
        assertThat(actual.name, is("山田 太郎"));
        assertThat(actual.age, is(20));
    }

参考ページ

Java - JAXB使い方メモ - Qiita
 ※非常に分かりやすくまとまっていました!

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?