【发布时间】:2011-07-11 02:32:56
【问题描述】:
我有一个 Maven 库项目,其中包含一些处理 xml 消息的类。每当我收到其中一条消息时,我都会使用我编写的 xml 模式文件对其进行验证。为我进行验证的代码如下所示:
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();
}
}
}
是的,xml 将使用架构文件进行验证。
现在来了:我想在 servlet 中使用我的小库(在 tomcat 中运行),但是在那里找不到 .xsd 文件:(
当然,我可以将 .xsd 文件存储在其他地方,例如直接在公司服务器上并通过 http 检索它,但我认为将其包含在 .jar 中是确保库和架构版本的更好解决方案适合。
你有什么想法吗?
提前致谢:
吉姆
【问题讨论】:
标签: java xml servlets jar schema