我正在尝试使用本地 DTD 验证我的 XML,我对此进行了谷歌搜索,然后我得到了一些代码,这是我的代码。
public Document buildDocument(File receivedFile) {
Document doc = null;
try {
logger.info("Inside buildDocument() , create a new DocumentBuilderFactory");
// create a new DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
// use the factory to create a documentbuilder
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
@Override
public void fatalError(SAXParseException exception) throws SAXException {
System.err.println("fatalError: " + exception);
}
@Override
public void error(SAXParseException exception) throws SAXException {
System.err.println("error: " + exception);
}
@Override
public void warning(SAXParseException exception) throws SAXException {
System.err.println("warning: " + exception);
}
});
builder.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
if (systemId.contains("xyz.com/remote.dtd")) {
return new InputSource(FileUtils.readFileToString(
new File("C:\\Users\\xyz\\local.dtd"));
} else {
return null;
}
}
});
doc = builder.parse(new InputSource(new StringReader(FileUtils.readFileToString(receivedFile, "UTF-16"))));
} catch (ParserConfigurationException | SAXException | IOException e) {
logger.warn("Opps got error while buiding document", e);
}
return doc;
注意:我的 XML 编码类型为 UTF-16
更新:在读取文件时删除了 UF-16,看起来 DTD 正在尝试进行编译并且它抛出以下错误,
latin-entities.dtd(系统找不到指定的路径)
这是否意味着这个 DTD 正在寻找依赖 DTD??
相关分类