XMLからオブジェクトを作る

テストクラスを作るとき、入れ子になったオブジェクトをJavaのコードで記述するのがめんどくさいので。

XMLのデータ

こんな感じ。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE bodybuilder>
<bodybuilder>
  <list>
    <add value="value"/>
    <add value="値"/>
    <add>
      <!-- 入れ子のList -->
      <list>
        <add value="nested value"/>
        <add value="入れ子の値"/>
      </list>
    </add>
    <add>
      <!-- Map その1 -->
      <map>
        <foo value="bar"/>
        <hoge value="hogera"/>
      </map>
    </add>
    <add>
      <!-- Map その2 -->
      <map>
        <put name="bar" value="foo"/>
        <put name="hogera" value="hoge"/>
      </map>
    </add>
    <add>
      <!-- 配列 -->
      <array type="int">
        <elem value="0"/>
        <elem value="1"/>
        <elem value="2"/>
      </array>
    </add>
    <add>
      <!-- Bean -->
      <bean type="sample.SampleBean">
        <id value="9" type="int"/>
        <value value="Beanの値"/>
        <subBean>
          <!-- 入れ子のBean その1 -->
          <bean type="sample.SampleBean">
            <prop name="id" value="99" type="int"/>
            <prop name="value" value="入れ子の値 その1"/>
            <prop name="subBean">
              <!-- 入れ子のBean その2 -->
              <bean type="sample.SampleBean">
                <prop name="id" value="999" type="int"/>
                <prop name="value" value="入れ子の値 その2"/>
              </bean>
            </prop>
          </bean>
        </subBean>
      </bean>
    </add>
  </list>
</bodybuilder>

実行時のコード

こんな感じ。


package sample;

import bodybuilder.Bullworker;
import bodybuilder.viewer.Viewer;

public class Sample {

public static void main(String[] args) {
Bullworker bullworker = new Bullworker(
"C:\\eclipse3\\workspace\\bodybuilder\\data\\sample.xml");
Object obj = bullworker.getMuscle();
Viewer.dump(obj);
}

}

サンプルの実行結果

こんな感じ。


ArrayList(7) {
[0]=>
String(5) "value"
[1]=>
String(1) "値"
[2]=>
ArrayList(2) {
[0]=>
String(12) "nested value"
[1]=>
String(5) "入れ子の値"
}
[3]=>
HashMap(2) {
["foo"]=>
String(3) "bar"
["hoge"]=>
String(6) "hogera"
}
[4]=>
HashMap(2) {
["hogera"]=>
String(4) "hoge"
["bar"]=>
String(3) "foo"
}
[5]=>
Integer[3] {
[0]=>
Integer "0"
[1]=>
Integer "1"
[2]=>
Integer "2"
}
[6]=>
sample.SampleBean {
["value"]=>
String(6) "Beanの値"
["subBean"]=>
sample.SampleBean {
["value"]=>
String(9) "入れ子の値 その1"
["subBean"]=>
sample.SampleBean {
["value"]=>
String(9) "入れ子の値 その2"
["subBean"]=>
null
["id"]=>
Integer "999"
}
["id"]=>
Integer "99"
}
["id"]=>
Integer "9"
}
}

TODO

  • サーブレットAPIへの対応。
    • MockRunner、StrutsTestCaseへの対応。
  • オブジェクトを再帰的に比較するAssertクラスの作成。
  • XMLの一ファイルを一テストケースとするテストユーティリティの作成。
  • ロギングの追加。
  • コンストラクタへの対応。

その他

Eclipseのプロジェクト一式*1

*1:要 Commons BeanUtils/Logging、JDOM、Xerces