I have several classes with JAXB annotations, I created several instances, and I need to test them on my XSD files. I should be able to get information about what is wrong when objects are invalid.
So far I have not been lucky, I know about this ValidationEventHandler class, but I can use it with the Unmarshaller class, the problem is that I have to check objects, not raw XML.
I have this code:
MyClass myObject = new MyClass();
JAXBContext jaxbContext = JAXBContext.newInstance("x.y.z");
JAXBSource jaxbSource = new JAXBSource(jaxbContext, myObject);
SchemaFactory factory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaFile = new StreamSource(getClass().getClassLoader()
.getResourceAsStream("mySchema.xsd"));
Schema schema = factory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(jaxbSource);
This code will work, it will check the object and throw an exception with a message, something like this:
cvc-pattern-valid: The value "12345678901" is not valid, respectfully for the pattern '\ d {10}' for type 'id'.]
, , , .