@634

JAXB(Java Architecture for XML Binding)

Advertisement

JAXBとは

JAXBはXML SchemaからJavaクラスを生成する技術(API)であり、JAXBバインディングコンパイラ仕様の総称である。

準備

入手

オフィシャルサイトより入手する。またはJava Web Services Developer Packに含まれている。

実行手順

  1. スキーマファイル作成
  2. スキーマコンパイル実行
jaxbではxmlに対応したクラスは、XMLスキーマファイルから自動生成する。JAXBのデフォルトスキーマ言語はXML Schemaで、他にDTDなどもサポートしている。

マーシャリングフレームワーク

JAXBはマーシャリングフレームワークと呼ばれるフレームワークを利用している。JavaオブジェクトからXMLへのバインディングをマーシャル(marshall)といい、その逆をアンマーシャル(Unmmarshall)という。
JAXBではマーシャルをjavax.xml.bind.Marshallerクラスが、アンマーシャルをjavax.xml.bind.Unmarshallerクラスがそれぞれ行う。
わかりやすい図がオフィシャルサイトにある→http://java.sun.com/xml/jaxb/about.html

実行サンプル(Quick Start)

簡単なXMLファイルを用意する。
emp.xml
<?xml version="1.0"?>
<employees>
    <emp id="1">
        <name>SMITH</name>
        <age>40</age>
    </emp>
    <emp id="2">
        <name>ALLEN</name>
        <age>30</age>
    </emp>
</employees>

emp.xmlに対するXML Schema定義ファイル
emp.xsd
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="employees">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element ref="emp" maxOccurs="unbounded"/>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>

  <xsd:element name="emp">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="name" type="xsd:string"/>
        <xsd:element name="age" type="xsd:int" />
      </xsd:sequence>
      <xsd:attribute name="id" type="xsd:int"/>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

Antビルドファイル
build.xml
<?xml version="1.0"?>
<project default="compile" basedir=".">
    <path id="classpath">
        <pathelement path="."/>
         <fileset dir="C:\Sun\jwsdp-1.6" includes="**/*.jar"/>
    </path>
   
    <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
        <classpath refid="classpath"/>
    </taskdef>
   
    <target name="compile">
        <xjc schema="schema/emp.xsd" target="src" package="jaxb"/>
    </target>
</project>

ant実行

Buildfile: C:\workspace\JAXB\build.xml
compile:
      [xjc] Consider using / so that XJC won't do unnecessary compilation
      [xjc] Compiling file:/C:/workspace/JAXB/schema/emp.xsd
      [xjc] Writing output to C:\workspace\JAXB\src
BUILD SUCCESSFUL
Total time: 14 seconds

ビルド結果
いっぱいできた。
図1:自動生成結果
図1:自動生成結果

パッケージ名は、build.xmlに記述した以下の定義より決定される。
<target name="compile">
    <xjc schema="schema/emp.xsd" target="src" package="jaxb"/>
</target>

各パッケージについて。
パッケージ名役割
親パッケージインタフェースとFactory
親パッケージ.implインタフェースの実装クラス
親パッケージ.runtimeコアとなる実行クラス
実際のプログラム内ではインタフェースを利用してコーディングを行う。

ここまででプログラムでの利用準備が整った。

XML読み込み(Unmarshal)

package crient;

import java.io.File;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import jaxb.EmpType;
import jaxb.EmployeesType;

public class EmployeesRead {
    public static void main(String[] args) throws Exception {
        JAXBContext context = JAXBContext.newInstance("jaxb");
        Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setValidating(true);
        EmployeesType employees = 
            (EmployeesType)unmarshaller.unmarshal(new File("xml/emp.xml"));
        List<EmpType> list = employees.getEmp();
        for(EmpType e : list){
            System.out.println(e.getId() + "\t" + 
                               e.getName() + "\t" + 
                               e.getAge());
        }
    }
}

実行結果
1	SMITH	40
2	ALLEN	30

XML出力(Marshal)

package crient;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import jaxb.EmpType;
import jaxb.EmployeesType;

public class EmpWrite {
    public static void main(String[] args) throws Exception {
        JAXBContext context = JAXBContext.newInstance("jaxb");
        Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setValidating(true);
        EmployeesType employees = 
            (EmployeesType)unmarshaller.unmarshal(new File("xml/emp.xml"));
        List<EmpType> list = employees.getEmp();
        for(EmpType e : list){
            Marshaller marshaller = context.createMarshaller();
            String filename = "xml/emp" + e.getId() + ".xml";
            marshaller.marshal(e, new FileOutputStream(new File(filename)));
            System.out.println("file:\t" + filename);
        }
    }
}

実行結果
file:	xml/emp1.xml
file:	xml/emp2.xml

まとめ

  • 基本的に自動生成。
  • 基本的に利用する側のクラスはインタフェースにのみ依存する。
  • XMLの構造が変更になると、場合によっては影響範囲が広い。
定義ファイルから情報を読み取り、任意の動作を行うフレームワークなどで大活躍しそう。JAXPとの使い分けが重要。

リンク

Advertisement

ショートカット

634
634ブログ
このカテゴリのトップページに戻る
Incubator(Pukiwiki)
634ラボ
   UIコレクションギャラリー
   ZO-3ジェネレーター

サイト検索


Y!ログール

ビリヤード