簡體   English   中英

沒有XML文件中包含的DTD聲明的XML文件的Java DTD驗證?

[英]Java DTD validation of XML files without the DTD declaration included in the XML File?

如何使用外部DTD文件來驗證我的XML文件?

DTD將位於某些URL上,例如http://localhost/example.dtd

並且XML文件中沒有引用DTD,因此我需要在Java servlet中執行此操作。

我正在使用JDOM來處理當前的XML文件。

任何幫助或指示表示贊賞

這個問題已經由stackoverflow處理

如果未在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())));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM