我已经构建了一个包含DTD文件的jar。我想在外部应用程序中使用此jar,其中DTD文件将用于XML文件。
我的问题是我如何才能从xml访问我的dtd文件(在.jar文件中)?
正如我们在其他配置文件中所说的那样说struts hibernate等,我们在xml中定义DTD,它们包含在.jar文件中。我想在我的jar文件中做同样但不能弄清楚方法,请帮忙。
答案 0 :(得分:3)
您可以实施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());
答案 1 :(得分:2)
以下是您的代码段...
将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");
所以,现在你有输入流,你可以随意使用它
希望它可以帮助你:)
答案 2 :(得分:1)
您需要创建一个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 */
}
}