正确加载包装在WAR中的XSD的方法?

NBW*_*NBW 3 xsd jaxb java-ee

我正在尝试验证在Web应用程序中解组的XML文件.xml文件本身位于Web应用程序部署目录之外,相应的XSD打包在WAR,类路径中的WEB-INF/classes/com/moi中

我一直无法弄清楚如何创建Schema对象,以便它相对于类路径获取XSD文件,而不是相对于工作目录硬编码路径.我想相对于类路径选择它,所以我可以在部署应用程序时(以及从单元测试运行时)找到它.下面的示例代码可以查找相对于工作目录的代码.

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;
Run Code Online (Sandbox Code Playgroud)

环境使用JAXB2/JDK 1.6.0_22/JavaEE6.思考?

bdo*_*han 8

您可以执行以下操作:

ClassLoader classLoader = Foo.class.getClassLoader();
InputStream xsdStream = classLoader.getResourceAsStream("com/moi/foo.xsd");
StreamSource xsdSource = new StreamSource(xsdStream);
Schema schema = sf.newSchema(xsdSource);
Run Code Online (Sandbox Code Playgroud)

  • 啊,你是对的,我错过了.是时候喝杯咖啡;-)感谢您的提示,您的博客也有一些好的内容. (2认同)