简体   繁体   中英

Unmarshal xml file with Moxy validating against multiple XML schemas

I am trying to unmarshal a XML file using EclipseLink MOXy 2.6 against multiple XML schemas - common.xsd and userOfCommon.xsd .
userOfCommon.xsd includes common.xsd and uses certain types defined in it.

I you want validation you have to set the unmarshaller like this:

Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

Source common = new StreamSource(this.getClass().getResourceAsStream("xsd/common.xsd"));
Source userOfCommon = new StreamSource(this.getClass().getResourceAsStream("xsd/userOfCommon.xsd"));

Schema schema = sf.newSchema(new Source[] {common, userOfCommon});
unmarshaller.setSchema(sf.newSchema(schema));

But setting the schema gives an error saying "Failing to resolve the 'Some ComplexType Name' to a(n) 'type definition' component."

I tried to set the schema as a file name like this

Schema schema = sf.newSchema(new File("xsd/userOfCommon.xsd"));

And it works. But I want to set the schema as Source items in order for it to be loaded from the classpath.

Any suggestions how to achieve this?

Actually the answer given here https://stackoverflow.com/a/1105871/4243908 works in this situation.

I had to set a custom ResourceResolver in the SchemaFactory like this

sf.setResourceResolver(new ResourceResolver());

The code for the ResourceResolver is available here

In that case there is no need to import multiple schema sources. You can just import the main schema source like this:

Schema schema = sf.newSchema(userOfCommon);

However I still have not figured out how to achieve it with multiple schema sources and without using custom ResourceResolver.

try using location while creating StreamSource as below:

Source common = new StreamSource(this.getClass().getResource("xsd/common.xsd").toString());
Source userOfCommon = new StreamSource(this.getClass().getResource("xsd/userOfCommon.xsd").toString());

the location is used to resolve schema imports relatively

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