1
我正在使用以下代碼片段來編寫XML文件。如果文檔無效,我需要拋出異常。我如何在這段代碼中進行驗證?使用dtd進行XML驗證
private static void writeToFile(Node node, File file) throws Exception {
TransformerFactory tf = TransformerFactory.newInstance();
tf.setAttribute("indent-number", new Integer(4));
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "schema.dtd");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(new DOMSource(node), new StreamResult(new FileWriter(file)));
}
這可能會對你有所幫助:http://stackoverflow.com/questions/1096365/validate-an-xml-file-against-local-dtd-file-with-java – Alvin