如何从servlet上下文中的jar文件中读取xml架构

我有一个maven库项目,有一些类来处理xml消息。 每当我收到其中一条消息时,我都会使用我编写的xml架构文件对其进行validation。 为我进行validation的代码如下所示:

public static Document parseXML(final String xml) throws JDOMException, IOException { SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser", true); builder.setFeature("http://apache.org/xml/features/validation/schema", true); URL location = CMPMessage.getClass().getResource(XML_SCHEMA_LOCATION); if (null == location) { throw new IOException("Unable to load schema definition file."); } builder.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", "http://www.mycompany.de/MyProtocol " + location); return builder.build(new StringReader(xml)); } 

XML_SCHEMA_LOCATION是这样的:

 private static final String XML_SCHEMA_LOCATION = "/ConvertMessageProtocol.xsd"; 

.xsd文件位于src/main/resources ,感谢maven,一切都很完美:当告诉maven制作包时,.xsd文件会包含在.jar中。 我做了一个简单的测试项目来检查是否真的会找到.xsd文件。 源代码如下:

 import java.io.IOException; import org.jdom.JDOMException; import de.mycomp.MyMessage; public class Main { public static void main(final String[] args) { try { MyMessage.parseXML(args[0]); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

是的,将使用模式文件validationxml。

现在它来了:我想在servlet中使用我的小库(在tomcat中运行),但在那里,找不到.xsd文件:(

当然,我可以将.xsd文件存储在其他地方,例如直接在公司服务器上,并通过http检索它,但我认为将它包含在.jar中是更好的解决方案,以确保libs和模式版本适合。

你有什么想法吗?

提前致谢:

吉姆

分配

 private static final String XML_SCHEMA_LOCATION = getPath("/ConvertMessageProtocol.xsd"); public static String getPath(String path){ return UtilityClass.class.getResource(path).toString(); } 

问题是您的servlet应用程序正在/没有文件的地方查找文件。