How to validate against schema in JAXB 2.0 without marshalling?

前端 未结 3 1368
时光说笑
时光说笑 2020-11-30 20:11

I need to validate my JAXB objects before marshalling to an XML file. Prior to JAXB 2.0, one could use a javax.xml.bind.Validator. But that has been deprecated so I\'m try

3条回答
  •  無奈伤痛
    2020-11-30 21:10

    This how we did it. I had to find a way to validate the xml file versus an xsd corresponding to the version of the xml since we have many apps using different versions of the xml content.

    I didn't really find any good examples on the net and finally finished with this. Hope this will help.

    ValidationEventCollector vec = new ValidationEventCollector();
    
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    
    URL xsdURL = getClass().getResource("/xsd/" + xsd);
    Schema schema = sf.newSchema(xsdURL);
    
    //You should change your jaxbContext here for your stuff....
    Unmarshaller um = (getJAXBContext(NotificationReponseEnum.NOTIFICATION, notificationWrapper.getEnteteNotification().getTypeNotification()))
        .createUnmarshaller();
    um.setSchema(schema);
    
    try {
        StringReader reader = new StringReader(xml);
        um.setEventHandler(vec);
        um.unmarshal(reader);
    } catch (javax.xml.bind.UnmarshalException ex) {
        if (vec != null && vec.hasEvents()) {
            erreurs = new ArrayList < MessageErreur > ();
            for (ValidationEvent ve: vec.getEvents()) {
                MessageErreur erreur = new MessageErreur();
                String msg = ve.getMessage();
                ValidationEventLocator vel = ve.getLocator();
                int numLigne = vel.getLineNumber();
                int numColonne = vel.getColumnNumber();
                erreur.setMessage(msg);
                msgErreur.setCode(ve.getSeverity())
                erreur.setException(ve.getLinkedException());
                erreur.setPosition(numLigne, numColonne);
                erreurs.add(erreur);
    
                logger.debug("Erreur de validation xml" + "erreur : " + numLigne + "." + numColonne + ": " + msg);
            }
        }
    }
    

提交回复
热议问题