I am currently using the DOM, but I want to use an external DTD with my XML file. With SAX you can parse the external DTD and associate it wih the XML file. How do I do that with the DOM?
Created May 4, 2012
Davanum Srinivas If you are using JAXP from Sun there are two things you can do.
First, use the com.sun.xml.tree.XmlDocument's setDoctype method as shown below.
XmlDocument doc = new XmlDocument (); ... // add a DTD, for fun doc.setDoctype ( null, // no public identifier "http://www.example.com/xml/dtd1.dtd", null // no internal subset ); ...There is a full example (main.java) at http://developer.java.sun.com/developer/products/xml/examples/#building
Second, you can use setEntityResolver method of javax.xml.parsers.DocumentBuilder to customize how the external DTD's are resolved. Here's an example from the docs.
import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; public class MyResolver implements EntityResolver { public InputSource resolveEntity (String publicId, String systemId) { if (systemId.equals("http://www.myhost.com/today")) { // return a special input source MyReader reader = new MyReader(); return new InputSource(reader); } else { // use the default behaviour return null; } } }