简体   繁体   English

没有XML文件中包含的DTD声明的XML文件的Java DTD验证?

[英]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? 如何使用外部DTD文件来验证我的XML文件?

The DTD will be located on some url eg http://localhost/example.dtd DTD将位于某些URL上,例如http://localhost/example.dtd

and the DTD is not referenced in the XML file, so I need to do this in my Java servlet. 并且XML文件中没有引用DTD,因此我需要在Java servlet中执行此操作。

I am using JDOM for my current processing of XML files. 我正在使用JDOM来处理当前的XML文件。

Any help or pointers is appreciated 任何帮助或指示表示赞赏

这个问题已经由stackoverflow处理

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: 如果未在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