1

How can I use an external DTD file to validate my XML file against?

The DTD will be located on some url e.g. http://localhost/example.dtd

and the DTD is not referenced in the XML file, so I need to do this in my Java servlet.

I am using JDOM for my current processing of XML files.

Any help or pointers is appreciated

anonymous
  • 2,294
  • 5
  • 23
  • 27

1 Answers1

3

If the DTD is not specified in the XML file, you can use a Transformer to add it in and then parse it as shown below:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();

//parse file into DOM
Document doc = db.parse(new File("file.xml"));
DOMSource source = new DOMSource(doc);

//now use a transformer to add the DTD element
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "/path/to/file.dtd");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);

//finally parse the result. 
//this will throw an exception if the doc is invalid
db.parse(new InputSource(new StringReader(writer.toString())));
dogbane
  • 266,786
  • 75
  • 396
  • 414