JavaでXML
今日はJavaでXMLを扱ってみる。
最近はXMLバインディングツールが多々あるようだが、
Castorを使用してみた。
Castorを使用する場合はマッピングファイルさえ正しく記述されていれば
プログラムは超楽。
以下に単価、タイトル、タイプをメンバとした本クラスを
リストとした本一覧クラスをXMLで扱うクラスを作ってみた。
以下、マッピングファイルの定義
<!DOCTYPE databases PUBLIC "-//EXOLAB/Castor Mapping DTD Version 1.0//EN"
"http://castor.exolab.org/mapping.dtd">
本一覧クラスをXMLで操作するエンティティマネジャーは以下。
public class BookListEntityManager {private String xmlPath;
private String mappingPath;
public String getMappingPath() {
return mappingPath;
}public void setMappingPath(String mappingPath) {
this.mappingPath = mappingPath;
}public BookList getBookList () {
BookList bookList = null;
try {
// マッピングファイルを読み込み
Mapping map = new Mapping();
map.loadMapping(this.mappingPath);
// Fileオブジェクトを生成し読み込みファイルを作成
File file = new File(xmlPath);
Reader read = new FileReader(file);
// アンマーシャル(読込)を行うためのアンマーシャルオブジェクトを生成
Unmarshaller unmarshaller = new Unmarshaller(map);
// アンマーシャル
bookList = (BookList) unmarshaller.unmarshal(read);
return bookList;
} catch (FileNotFoundException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
} catch (MappingException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
} catch (MarshalException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
} catch (ValidationException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
return null;
}
public void updateBookList (BookList bookList) {
try {
// ファイルオブジェクトから書き込みファイルを生成
File file = new File(xmlPath);
Writer writer = new FileWriter(file);
// マッピングファイルを読み込み
Mapping map = new Mapping();
map.loadMapping(this.mappingPath);
// マーシャルオブジェクトの作成
Marshaller marshaller = new Marshaller(writer);
marshaller.setMapping(map);
// マーシャル(書き込み)
marshaller.marshal(bookList);
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
} catch (MappingException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
} catch (MarshalException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
} catch (ValidationException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}
public String getXmlPath() {
return xmlPath;
}public void setXmlPath(String xmlPath) {
this.xmlPath = xmlPath;
}
}
これだけで以下のようなXMLの読書きを行えるようになった。
うーん。なんて簡単なんだ。いいねCastor。
一応本クラス、本一覧クラスの内容も。
// 本クラス
package entity;
public class Book {
private int price;
private String title;
private String type;
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
// 本一覧クラス
package entity;import java.util.List;
public class BookList {
private List books;
public List getBooks() {
return books;
}
public void setBooks(List books) {
this.books = books;
}
}