针对XML模式的通用XML文件验证器(XSD文件)

问题描述 投票:1回答:1

我想用JAXB创建一个通用的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);

而且我也无法映射unmarshaled对象并将其设置为在参数中传递的E obj。我知道它可以返回,但我被要求将其设置为该参数。请帮忙。提前致谢

java xml generics xsd jaxb
1个回答
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:

import XmlClasses.ObjectFactory;

哪个仍然使它不完全通用,如何采取通用的ObjectFactory?

© www.soinside.com 2019 - 2024. All rights reserved.