4

I am trying to validate an XML file being unmarshalled within a web app. The xml file itself is outside the web app deployment directory and the corresponding XSD is packaged in the WAR, in the classpath, in WEB-INF/classes/com/moi

I have been unable to figure out how to create the Schema object such that it picks up the XSD file relative to the classpath vs. hard coding a path relative to the working directory. I want to pick it up relative to the classpath so I can find it when the application is deployed (as well as when its run from the unit test). The sample code below, which works, looks for it relative to the working directory.

JAXBContext context;
context = JAXBContext.newInstance(Foo.class);
Unmarshaller unMarshaller = context.createUnmarshaller();

SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File("src/com/moi/foo.xsd"));

unMarshaller.setSchema(schema);
Object xmlObject = Foo.class.cast(unMarshaller.unmarshal(new File("C:\\foo.xml")));
return (Foo) xmlObject;

The environment is using JAXB2/JDK 1.6.0_22/JavaEE6. Thoughts?

NBW
  • 1,467
  • 2
  • 18
  • 27

2 Answers2

11

You can do the following:

ClassLoader classLoader = Foo.class.getClassLoader();
InputStream xsdStream = classLoader.getResourceAsStream("com/moi/foo.xsd");
StreamSource xsdSource = new StreamSource(xsdStream);
Schema schema = sf.newSchema(xsdSource);
bidisha mukherjee
  • 715
  • 1
  • 10
  • 20
bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • Hi Blaise - Schema.newSchema() only takes a Scource, a File, a URL, Source[], or nothing for its parameter. It doesn't take a StreamSource as you have in this example. – NBW Mar 15 '11 at 12:52
  • @NBW - StreamSource implements the Source interface, so you can use it as a parameter to the newSchema method. Check out my example where newSchema is used on a JAXBSource: http://bdoughan.blogspot.com/2010/11/validate-jaxb-object-model-with-xml.html – bdoughan Mar 15 '11 at 13:08
  • 2
    Ah you are correct, I missed that. Time to grab a cup of coffee ;-) Thanks for your tip and your blog has some good content too. – NBW Mar 15 '11 at 13:56
0

If we have multiple XSD which is using import internally for them. then this does not work. It is loading only one file so not able to load other imported xsd schema.

this answer works fine. https://stackoverflow.com/a/9280611/4498746