JAXB 入力[2]
【「Java SE 6完全攻略」第73回 JAXB その1】
http://itpro.nikkeibp.co.jp/article/COLUMN/20080530/305406/?ST=develop&P=3
を参考に、JAXBを使って、XMLを読み込ませ、コンソール画面に出力するプログラムを作成してみた。
手順
1)定義ファイルを作成(simple.xsd)
2)コマンドプロンプトを立ち上げ、1)が保存してあるところまで行き、以下のコマンドする。
(ただし、「JDK1.6(ここでは、jdk1.6.0_17))」上をインストールされていること)
xjc simple.xsd
→コマンド後、"generated"以下に、「ObjectFactory.java」と「Person.java」が作成される。
3) Eclipseを立ち上げ、パッケージ「generated」を作成し、
「ObjectFactory.java」と「Person.java」をその中にぶち込む
4)ソースを書く
サンプル
simple.xsd(定義ファイル)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="">http://www.w3.org/2001/XMLSchema">
<xs:element name="person">
<xs:complexType>
<xs:attribute name="name" type="xs:string"/>
<xs:attribute name="age" type="xs:int"/>
</xs:complexType>
</xs:element>
</xs:schema>
simple.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person name="Neil Young" age="62" />
メイン(省略)
UnmarshallerSample.java
package common;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import generated.Person;
public class UnmarshallerSample {
public UnmarshallerSample() {
}
/**
* XMLファイルをコンソールに出力
*
* @param inputFilePath 入力するXMLファイルのパス(絶対パス)
* @return void
* @exception javax.xml.bind.JAXBContext 引数不正, 画像生成失敗時などに起こりうる例外。
* @see <a href="">http://itpro.nikkeibp.co.jp/article/COLUMN/20080530/305406/?ST=develop&P=3">参考1</a>
* @see <a href="">http://takuan93.blog62.fc2.com/blog-entry-38.html">参考2</a>
* @version 0.0.1
*/
public void Unmarshaller(String inputFilePath) throws JAXBException {
// 1. JAXBContextオブジェクトの生成
// 引数はパッケージもしくはクラス
JAXBContext context
= JAXBContext.newInstance("generated" );
// 2. Unmarsallerオブジェクトの取得
Unmarshaller unmarshaller = context.createUnmarshaller();
File inputFile = new File(inputFilePath);
// 3. アンマーシャリング
// 戻り値はルートタグに相当するクラス
Object obj = unmarshaller.unmarshal(inputFile);
Person artists = (Person)obj;
// 4. 変換されたオブジェクトにアクセス
System.out.println("Name: " + artists.getName());
System.out.println("Age: " + artists.getAge());
}
}