次のようなことができます。
Foo
ルートモデルオブジェクトにバージョンフィールドを追加します。
package forum12218164;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Foo {
@XmlAttribute
public static final String VERSION = "123";
private String bar;
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
デモ
デモコードでは、StAXパーサーを利用して、アンマーシャル操作を安全に実行できるかどうかを判断する前に、バージョン属性を確認します。
package forum12218164;
import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
// Create the JAXBContext
JAXBContext jc = JAXBContext.newInstance(Foo.class);
// Create an XMLStreamReader on XML input
XMLInputFactory xif = XMLInputFactory.newFactory();
StreamSource xml = new StreamSource("src/forum12218164/input.xml");
XMLStreamReader xsr = xif.createXMLStreamReader(xml);
// Check the version attribute
xsr.nextTag(); // Advance to root element
String version = xsr.getAttributeValue("", "VERSION");
if(!version.equals(Foo.VERSION)) {
// Do something if the version is incompatible
throw new RuntimeException("VERSION MISMATCH");
}
// Unmarshal for StAX XMLStreamReader
Unmarshaller unmarshaller = jc.createUnmarshaller();
Foo foo = (Foo) unmarshaller.unmarshal(xsr);
// Marshal the Object
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(foo, System.out);
}
}
有効なユースケース
input.xml / Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo VERSION="123">
<bar>ABC</bar>
</foo>
無効なユースケース
input.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo VERSION="1234">
<bar>ABC</bar>
</foo>
出力
Exception in thread "main" java.lang.RuntimeException: VERSION MISMATCH
at forum12218164.Demo.main(Demo.java:23)