328.5. JAXB と StAX を使用してコレクションを反復処理する
まず、JAXB オブジェクトがあるとします。
たとえば、ラッパーオブジェクト内のレコードのリスト:
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "records")
public class Records {
@XmlElement(required = true)
protected List<Record> record;
public List<Record> getRecord() {
if (record == null) {
record = new ArrayList<Record>();
}
return record;
}
}および
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "record", propOrder = { "key", "value" })
public class Record {
@XmlAttribute(required = true)
protected String key;
@XmlAttribute(required = true)
protected String value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}次に、処理する XML ファイルを取得します。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <records> <record value="v0" key="0"/> <record value="v1" key="1"/> <record value="v2" key="2"/> <record value="v3" key="3"/> <record value="v4" key="4"/> <record value="v5" key="5"/> </record>
StAX コンポーネントは、Camel Splitter で XML 要素を反復するときに使用できる StAXBuilder を提供します。
from("file:target/in")
.split(stax(Record.class)).streaming()
.to("mock:records");
stax は、Java コードで静的にインポートできる org.apache.camel.component.stax.StAXBuilder の静的メソッドです。stax ビルダーは、デフォルトで、それが使用する XMLReader の名前空間を認識します。Camel 2.11.1 以降では、以下に示すように、boolean パラメーターを false に設定することでこれをオフにすることができます。
from("file:target/in")
.split(stax(Record.class, false)).streaming()
.to("mock:records");328.5.1. XML DSL を使用した前の例
上記の例は、XML DSL で次のように実装できます。