简体   繁体   中英

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 eg http://localhost/example.dtd

and the 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

这个问题已经由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:

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())));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM