我使用Jaxb将XML解组为java对象。我需要知道XML中的新属性/元素何时失败。但是,默认情况下,unmarshaller会忽略新的元素/属性。
当XML中存在未在POJO中指定的新属性/元素时,是否存在可以设置为失败的配置?
我的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);
答案 0 :(得分:4)
您需要调用Unmarshaller.setEventHandler()
以使无效的XML内容失败。
答案 1 :(得分:2)
您可以通过在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()
设置)相结合。