2011年10月5日水曜日

Castorの使い方「Unmarshal」

Castorを使い始めて間もないが、基本的にネット上に転がっている情報ではUnmarshalについて詳しく載っていなくて
英語もあまり得意でない僕にとっては、苦戦を強いられた。。。

まずUnmarshalは、XML→Objectのこと。
おいおいそこからかよ。。。っていう気持ちを抑えて無駄にメモることにする。

使い道はいろいろあるだろうけど、
自分の場合はWebAPIの返却をオブジェクトとして扱いたかったから。
(XSDとか提供されていない場合に)

Unmarshalを行うコードは以下のようになる。
public class CastorTest {

 private static Mapping mapping;
 private static Unmarshaller unmar;
 private static CategoryList categoryList;

 public CastorTest() {

 }

 private void initialize() {
  mapping = new Mapping();
  try {
   mapping.loadMapping("xml/categoryList_mapping.xml");
   System.out.println("categoryList_mapping succeeded.");
  } catch (Exception e) {

  }
 }

 private void HandleCategoryList() {
  try {
   unmar = new Unmarshaller(mapping);
   categoryList = (CategoryList) unmar.unmarshal(new InputSource(
     new FileReader("xml/categoryList.xml")));
   Category[] categories = new Category[categoryList.getCategories().getCategories().size()];
   categories = (Category[]) categoryList.getCategories().getCategories().toArray();

   for (int i = 0; i < categories.length; i++) {
    Category category = categories[i];
    System.out.print(category.getName());
   }

  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static void main(String[] args) {
  CastorTest test = new CastorTest();
  test.initialize();
  try {
   test.HandleCategoryList();
  } catch (Exception e) {
   System.out.println(e);
  }

 }
}
僕がつまづいたのは、Mapping定義を示すXMLファイルの書き方。。。 Unmarchalを行うXMLとそのMapping定義のXMLを続けて以下に示す。 ▼変換したいXML


 
  
   002
   名前1
   キー1
   親1
  
  
   001
   名前2
   キー2
   親2
  
 

▼Mapping定義


 
  
  
   
  
 
 
  
   
  
 
 
  
   
  
  
   
  
  
   
  
  
   
  
 


はまったところだけを書いておくと、、、、

->変換するXMLはエンコーディング指定をSJISにしないとだめ!
->ArrayListへ詰めるには上記のようにしなきゃだめ!
->基本的にclassタグにはtypeを書いておけ!
->たぶんclassは入れ子になっちゃダメ?

こんくらいかな。
誰かが救われれば本望です。

0 件のコメント:

コメントを投稿