ユースケースをサポートするために、 JAXB (JSR-222)アノテーションを含む Java モデルを使用できます。複数回発生する可能性のある要素List
は、Java モデルのプロパティに対応します。以下は、ドキュメントをマップする方法の例です。
テーブル
注釈を使用し@XmlElementWrapper
てグループ化要素を追加し、注釈を使用@XmlElement
してコレクション内の項目の要素名を設定します。
package forum11543081;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="root-element")
@XmlAccessorType(XmlAccessType.FIELD)
public class Table {
@XmlElementWrapper(name="table")
@XmlElement(name="row")
private List<Row> rows;
}
行
プロパティ/フィールドの名前が結果の XML 要素の名前と一致する場合、注釈は必要ありません。
package forum11543081;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Row {
private List<String> d;
}
デモ
以下は、マッピングが機能することを証明するスタンドアロンの例です。
package forum11543081;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Table.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11543081/input.xml");
Table table = (Table) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(table, System.out);
}
}
input.xml/出力
<root-element>
<table>
<row>
<d>data1</d>
<d>data2</d>
<d>data3</d>
</row>
<row>
<d>data4</d>
<d>data5</d>
<d>data6</d>
</row>
</table>
</root-element>
詳細については