Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to load XSD packaged in a WAR?

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?

like image 346
NBW Avatar asked Dec 28 '22 23:12

NBW


1 Answers

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);
like image 55
bdoughan Avatar answered Feb 11 '23 12:02

bdoughan