gpt4 book ai didi

java - 针对 XML 架构(XSD 文件)的通用 XML 文件 validator

转载 作者:太空宇宙 更新时间:2023-11-04 10:11:13 27 4
gpt4 key购买 nike

我想使用 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;
}
}

}

以下行给出警告 ->

Type safety: Unchecked cast from Object to JAXBElement

javax.xml.bind.JAXBElement<Document>  doc=(javax.xml.bind.JAXBElement<Document>) unmarshaller.unmarshal(xmlFile);

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

最佳答案

我更改为以下并且有效:

    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 obj2.我正在使用 JAXB 生成的类中的 ObjectFactory :

import XmlClasses.ObjectFactory;

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

关于java - 针对 XML 架构(XSD 文件)的通用 XML 文件 validator ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52295828/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com