我正在尝试解组与JAXB类不匹配的XML字符串。我希望这会抛出一个异常,但是会返回一个新的JAXB对象。
xmlStr(输入XML)
<urn1:RgBad
xmlns:urn1="urn:none">
</urn1:RgBad>
更正XML
<urn:Rg
xmlns:urn="urn:test"
代码
(clazz = Rg.class)
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StreamSource source = new StreamSource(new StringReader(xmlStr));
//Returns an actual Rg object, even though the source root element and namespace are different.
(unmarshaller.unmarshal(source, clazz)).getValue();
答案 0 :(得分:0)
您可以尝试添加架构以在使用JAXB时验证xml文件
try {
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File( "yourSchema.xsd" ));
JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName());
Unmarshaller u = jc.createUnmarshaller();
u.setSchema(schema);
u.setEventHandler(ehdler);
obj = u.unmarshal(xml);
} catch (JAXBException e) {
} finally {
}