简体   繁体   中英

Validation with JAXB

My problem is:

check if an XML document is well-formed respect to its schema.

In particular, I would like to be able to use a "validator" that returns NULL in case of any error (problems with minOccurs / maxOccurs, absence of tags, etc ...).

how can I extend/fix my code for implement my request?

    UDInfo temp = new UDInfo();

    try {
            File fileXML = new File(pathXML);
            SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
            Schema schema = sf.newSchema(new File(pathXSD)); 
            JAXBContext jaxbContext = JAXBContext.newInstance(UDInfo.class);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            jaxbUnmarshaller.setSchema(schema);
            jaxbUnmarshaller.setEventHandler(new MyValidationEventHandler());

            // if (validation is Ok) temp = (UDInfo) jaxbUnmarshaller.unmarshal(fileXML);
            // else temp = null;

    } catch (SAXException e) {
          e.printStackTrace();
    } catch (JAXBException ex) {
          Logger.getLogger(unMarsh.class.getName()).log(Level.SEVERE, null, ex);
    }

MyValidationEventHandler is:

public class MyValidationEventHandler implements ValidationEventHandler {

public boolean handleEvent(ValidationEvent event) {
    System.out.println("\nEVENT");
    System.out.println("SEVERITY:  " + event.getSeverity());
    System.out.println("MESSAGE:  " + event.getMessage());
    System.out.println("LINKED EXCEPTION:  " + event.getLinkedException());
    return true;
}    }

You could do something like the following:

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        jaxbUnmarshaller.setSchema(schema);
        MyValidationEventHandler myValidationEventHandler();
        jaxbUnmarshaller.setEventHandler(myValidationEventHandler);
        jaxbUnmarshaller.unmarshal(xml);
        myValidationEventHandler.getMyState();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM