Correct way to load XSD packaged in WAR?

I am trying to validate an XML file that is not supported in a web application. The xml file itself is outside the web application deployment directory, and the corresponding XSD is packaged in a WAR in the class path in WEB-INF / classes / com / moi

I was not able to figure out how to create the Schema object so that it collects the XSD file relative to the class path and hardcoding the path relative to the working directory. I want to raise it relative to the classpath to find it when the application is deployed (and also when starting from unit test). The sample code below that 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 uses JAXB2 / JDK 1.6.0_22 / JavaEE6. Thoughts?

+3
source share
2 answers

:

ClassLoader classLoader = Foo.class.getClassLoader();
InputStream xsdStream = classLoader.getResourceAsStream("com/moi/foo.xsd");
StreamSource xsdSource = new StreamSource(xsdStream);
Schema schema = sf.newSchema(xsdSource);
+7
0

All Articles