I have build a jar which contains a DTD file. I want to use this jar in an external application, in which the DTD file will be used for an XML file.
My question is how can i make my dtd file (which is inside .jar file) accessible from xml?
As we do in other config files of let's say struts hibernate etc, we define DTD in xml which are included in .jar files. I wanna do same in my jar file but not able to figure out the way, Please help.
Rules. The document type declaration must appear at the start of the document (preceded only by the XML header) − it is not permitted anywhere else within the document. Similar to the DOCTYPE declaration, the element declarations must start with an exclamation mark.
An Internal DTD DeclarationIn the XML file, select "view source" to view the DTD. The DTD above is interpreted like this: ! DOCTYPE note defines that the root element of this document is note.
External DTDThey are accessed by specifying the system attributes which may be either the legal . dtd file or a valid URL. To reference it as external DTD, standalone attribute in the XML declaration must be set as no. This means, declaration includes information from the external source.
You can implement an 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;
}
}
}
and use it with your DocumentBuilder.setEntityResolver()
DocumentBuilder docBuilder = ...
docBuilder.setEntityResolver(new MyResolver());
Here is the code snippets for you...
Add DTD To JAR
Use Resolver class for DTD to place DTD to your 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 */
}
}
Load DTD From JAR
InputStream ins = this.getClass().getResourceAsStream("project/mypackage/File.dtd");
So, now you have inputstream and you can use it as you like
Hope it helps you :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With