Java DTD validation of XML files without the DTD declaration included in the XML File?
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 t开发者_JAVA技巧he 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
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())));
精彩评论