Reputation: 232
Does it possible to validate xml while unmarshaling by two xsd? I know that you unmarshal xml to object with several contexts by doing this:
context = JAXBContext.newInstance("onepackagecontext:secondpackagecontext");
I can use one schema for validation:
unmarshaller.setSchema(getSchema(url));
What could I do so that use two XSD for validation?
Upvotes: 2
Views: 3448
Reputation: 51
You can do like this:
final InputStream isMain = this.getClass().getResourceAsStream( "/real.xsd" );
final InputStream isImport=
this.getClass().getResourceAsStream( "/import.xsd" );
final InputStream isInclude =
this.getClass().getResourceAsStream( "/include.xsd" );
final Source include = new StreamSource( isInclude );
final Source imp = new StreamSource( isImport );
final Source main = new StreamSource( isMain );
final Source[] schemaFiles = new Source[] {
include, imp, main
};
final SchemaFactory sf = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI );
final Schema schema = sf.newSchema( schemaFiles );
final JAXBContext jc =
JAXBContext.newInstance( YourJaxb.class );
final Unmarshaller unmarshaller = jc.createUnmarshaller();
final JAXBElement<YourJaxb> jaxbElement =
unmarshaller.unmarshal(
YourJaxb.class );
final JAXBSource source = new JAXBSource( jc, jaxbElement.getValue() );
final ValidationErrorHandler val = new ValidationErrorHandler();
final Validator validator = schema.newValidator();
validator.setErrorHandler( val );
validator.validate( source );
Upvotes: 5
Reputation: 4137
I don't see a reason why this should work.
If there is no relation between the two schemas, this can be problematic
If you take a look for example at generation of Java classes from XSD - if you provide two unrelated XSDs to the generator, it may cause an attempt to create mutliple inheritance and issues like that. I suspect you might have some bad design here
What I do suggest is that you revisit the schemas , and see how you can unify them to one schema that will answer you needs.
Upvotes: 2