How to validate against schema in JAXB 2.0 without marshalling?

前端 未结 3 1359
时光说笑
时光说笑 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 20:54

    You could use a javax.xml.bind.util.JAXBSource (javadoc) and a javax.xml.validation.Validator (javadoc), throw in an implementation of org.xml.sax.ErrorHandler (javadoc) and do the following:

    import java.io.File;
    
    import javax.xml.XMLConstants;
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.util.JAXBSource;
    import javax.xml.validation.*;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            Customer customer = new Customer();
            customer.setName("Jane Doe");
            customer.getPhoneNumbers().add(new PhoneNumber());
            customer.getPhoneNumbers().add(new PhoneNumber());
            customer.getPhoneNumbers().add(new PhoneNumber());
    
            JAXBContext jc = JAXBContext.newInstance(Customer.class);
            JAXBSource source = new JAXBSource(jc, customer);
    
            SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
            Schema schema = sf.newSchema(new File("customer.xsd")); 
    
            Validator validator = schema.newValidator();
            validator.setErrorHandler(new MyErrorHandler());
            validator.validate(source);
        }
    
    }
    

    For More Information, See My Blog

    • http://blog.bdoughan.com/2010/11/validate-jaxb-object-model-with-xml.html

提交回复
热议问题