开发者

Proper way to load XSD packaged in a WAR?

开发者 https://www.devze.com 2023-02-17 00:35 出处:网络
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 classp

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 开发者_如何学Godirectory. 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 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

0

精彩评论

暂无评论...
验证码 换一张
取 消