简体   繁体   中英

JAXB. Validating XML by two xsd

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?

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 );

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.

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