当Jaxb解组时,希望未知属性出错
我正在使用Jaxb将XML解组为一个java对象。 我需要知道XML中的新属性/元素何时失效。 但是,默认情况下,解组器会忽略新的元素/属性。
当POJO中没有指定的XML中存在新的属性/元素时,是否可以设置配置失败?
我的POJO:
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "ROOT")
public class Model {
private A a;
public A getA() {
return a;
}
@XmlElement(name = "A")
public void setA(A a) {
this.a = a;
}
static class A {
String country;
public String getCountry() {
return country;
}
@XmlAttribute(name = "Country")
public void setCountry(String country) {
this.country = country;
}
}
}
代码解组:
JAXBContext jaxbContext = JAXBContext.newInstance(Model.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
String sample = "<ROOT>" +
"<A Country="0" NewAttribute="0"></A>" +
"<NEWELEMENT> </NEWELEMENT>" +
"</ROOT>";
InputStream stream = new ByteArrayInputStream(sample.getBytes(StandardCharsets.UTF_8));
Object unmarshal = jaxbUnmarshaller.unmarshal(stream);
您需要调用Unmarshaller.setEventHandler()
以使无效的XML内容失败。
您可以通过在Unmarshaller
上启用XML模式验证来阻止意外的内容。 如果你的POJO没有XML Schema,你可以在运行时从JAXBContext
生成一个Schema
对象,然后在Unmarshaller
上设置它。 默认情况下,如果XML文档对模式无效, Unmarshaller
将引发异常。
以下是一个如何做到这一点的例子:
JAXBContext jaxbContext = JAXBContext.newInstance(Model.class);
// Generate XML Schema from the JAXBContext
final List<ByteArrayOutputStream> schemaDocs = new ArrayList<ByteArrayOutputStream>();
jaxbContext.generateSchema(new SchemaOutputResolver() {
@Override
public Result createOutput(String namespaceUri, String suggestedFileName)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
StreamResult sr = new StreamResult(baos);
schemaDocs.add(baos);
sr.setSystemId(suggestedFileName);
return sr;
}
});
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
int size = schemaDocs.size();
Source[] schemaSources = new Source[size];
for (int i = 0; i < size; ++i) {
schemaSources[i] = new StreamSource(
new ByteArrayInputStream(schemaDocs.get(i).toByteArray()));
}
Schema s = sf.newSchema(schemaSources);
// Set the JAXP Schema object on your Unmarshaller.
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
jaxbUnmarshaller.setSchema(s);
String sample = "<ROOT>" +
"<A Country="0" NewAttribute="0"></A>" +
"<NEWELEMENT> </NEWELEMENT>" +
"</ROOT>";
InputStream stream = new ByteArrayInputStream(sample.getBytes("UTF-8"));
Object unmarshal = jaxbUnmarshaller.unmarshal(stream);
如果您希望收到关于多个错误的通知或过滤出您想要容忍的验证错误,请将其与通过上一个答案中建议的ValidationEventHandler(通过Unmarshaller.setEventHandler()
设置Unmarshaller.setEventHandler()
结合使用。
上一篇: Would like unknown attributes to error when Jaxb unmarshalling
下一篇: How to ignore elements/attributes in XML when mapping to objects using JAXB?