如何使用外部DTD文件来验证我的XML文件?
DTD将位于某个网址上,例如http://localhost/example.dtd
并且XML文件中没有引用DTD,所以我需要在我的Java servlet中执行此操作。
我正在使用JDOM来处理当前的XML文件。
任何帮助或指示表示赞赏
答案 0 :(得分:2)
此问题已由stackoverflow
处理答案 1 :(得分:2)
如果未在XML文件中指定DTD,您可以使用Transformer将其添加,然后解析它,如下所示:
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())));