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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With