如何使用外部DTD文件來驗證我的XML文件?XML文件中沒有包含DTD聲明的XML文件的Java DTD驗證?
DTD將位於某個URL上,例如http://localhost/example.dtd
並且XML文件中沒有引用DTD,所以我需要在我的Java servlet中執行此操作。
我正在使用JDOM來處理當前的XML文件處理。
任何幫助或指針表示讚賞
如何使用外部DTD文件來驗證我的XML文件?XML文件中沒有包含DTD聲明的XML文件的Java DTD驗證?
DTD將位於某個URL上,例如http://localhost/example.dtd
並且XML文件中沒有引用DTD,所以我需要在我的Java servlet中執行此操作。
我正在使用JDOM來處理當前的XML文件處理。
任何幫助或指針表示讚賞
處理如果在XML文件中沒有指定的DTD,你可以使用一個變壓器將其添加,然後解析它如下圖所示:
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())));
這個問題已經被stackoverflow
可以用JDOM來做到這一點嗎? – 2011-01-20 16:49:54