我想用JAXB创建一个通用的xmlFileValidator,该XMLFileValidator接受一个XML文件和一个模式文件,如果该文件有效,则返回根类的对象,否则抛出SAXException或JAXBException。
public class XmlValidateEventHandler implements ValidationEventHandler {
public static <E> void validator(File xsdFile, File xmlFile, E obj) throws SAXException, JAXBException
{
JAXBContext jaxbcontextobj = JaxbUtil.create_context_obj(new ObjectFactory());
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(xsdFile);
Unmarshaller unmarshaller = JaxbUtil.create_unmarshl_obj(jaxbcontextobj);
unmarshaller.setSchema(schema);
unmarshaller.setEventHandler(new XmlValidateEventHandler());
javax.xml.bind.JAXBElement<Document> doc = (javax.xml.bind.JAXBElement<Document>) unmarshaller.unmarshal(xmlFile);
Document d = doc.getValue();
obj=(E)d;
}
@Override
public boolean handleEvent(ValidationEvent event) {
Logger logger = utility.JaxbUtil.getLogger();
if(event.getSeverity() == ValidationEvent.ERROR || event.getSeverity() == ValidationEvent.FATAL_ERROR)
{
//Logger logger = Logger.getLogger(XmlValidateEventHandler.class);
logger.error("SEVERITY: " + event.getSeverity());
logger.error("MESSAGE: " + event.getMessage());
logger.error("LINKED EXCEPTION: " + event.getLinkedException());
logger.error("LINE NUMBER: " + event.getLocator().getLineNumber());
logger.error("COLUMN NUMBER: " + event.getLocator().getColumnNumber());
logger.error("***** Give XML is invalid aginst given XSD *****");
return false;
}
}
}
以下行给出警告->
类型安全性:未经检查的从Object到JAXBElement的投射
javax.xml.bind.JAXBElement<Document> doc=(javax.xml.bind.JAXBElement<Document>) unmarshaller.unmarshal(xmlFile);
而且我也无法映射未编组的对象并将其设置为在参数中传递的 E obj 。 我知道它可以返回,但已被要求将其设置为该参数。 请帮忙。 预先感谢
答案 0 :(得分:0)
我更改为以下内容,并且有效:
public static <E> E validator(File xsdFile, File xmlFile, E obj) throws SAXException, JAXBException
{
JAXBContext jaxbcontextobj = JaxbUtil.setContextObj(new ObjectFactory());
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(xsdFile);
Unmarshaller unmarshaller = JaxbUtil.setUnmarshlObj(jaxbcontextobj);
unmarshaller.setSchema(schema);
unmarshaller.setEventHandler(new XmlValidateEventHandler());
javax.xml.bind.JAXBElement<E> doc = (javax.xml.bind.JAXBElement<E>) unmarshaller.unmarshal(xmlFile);
E d = (E) doc.getValue();
return d;
}
但是现在仍然有开放性: 1.我仍然无法将对象映射到第三个参数-> E obj 2.我正在使用JAXB生成的类中的ObjectFactory:
导入XmlClasses.ObjectFactory;
哪些仍不能使其完全通用,如何采用通用ObjectFactory?