我正在尝试验证在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.思考?
您可以执行以下操作:
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)
归档时间: |
|
查看次数: |
5141 次 |
最近记录: |