我已经构建了一个包含DTD文件的jar。我想在外部应用程序中使用这个jar,其中DTD文件将用于XML文件。
我的问题是,如何使我的dtd文件(位于.jar文件中)可以从xml访问?
正如我们在struts-hibernate等的其他配置文件中所做的那样,我们在.jar文件中包含的xml中定义DTD。我想在我的jar文件中做同样的事情,但不知道该怎么做,请帮忙。
您可以实现org.xml.sax.EntityResolver
public class MyResolver implements EntityResolver {
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
if (systemId.contains("my.dtd")) {
InputStream myDtdRes = getClass().getResourceAsStream("/com/yourcompany/my.dtd");
return new InputSource(myDtdRes);
} else {
return null;
}
}
}
并将其与您的DocumentBuilder.setEntityResolver()
一起使用
DocumentBuilder docBuilder = ...
docBuilder.setEntityResolver(new MyResolver());
以下是您的代码片段。。。
将DTD添加到JAR
使用DTD的Resolver类将DTD放置到您的jar 中
DocumentBuilderFactory myFactory = xmlFactories.newDocumentBuilderFactory();
myFactory.setNamespaceAware(true);
myFactory.setValidating(false);
DocumentBuilder db = myFactory.newDocumentBuilder();
db.setEntityResolver(new EntityManager());
public class EntityManager implements EntityResolver
{
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
/* returns contents of DTD */
}
}
从JAR加载DTD
InputStream ins = this.getClass().getResourceAsStream("project/mypackage/File.dtd");
所以,现在你有了inputstream,你可以随心所欲地使用它
希望它能帮助你:)
您需要创建一个EntityResolver类,用于将DTD的公共或系统ID解析为您放置在JAR中的DTD的副本。
DocumentBuilderFactory factory = xmlFactories.newDocumentBuilderFactory();
factory.setNamespaceAware(true);
factory.setValidating(false);
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
documentBuilder.setEntityResolver(new EntityManager());
......
public class EntityManager implements EntityResolver {
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
/* code to check the public or system ID and return contents of DTD */
}
}