XMLReader 搜索相对于主应用程序而不是 XML 文件的 DTD 文件

XMLReader searches for DTD files relatively to main app instead of XML file

我正在尝试使用 Netbeans 作为 运行 一些 XML 解析 IDE。 我的项目在 F:\Project,我的 XML 在 D:\XML\data.xmlD:\XML\validation.dtd。 dtd 文件在我的 XML 中引用如下:

<!DOCTYPE softwarelist SYSTEM "validation.dtd">

但我不明白为什么 XMLReader 搜索的是相对于项目文件夹而不是 XML 文件夹的 dtd?

解析代码如下:

    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(false);
        XMLReader xmlReader = spf.newSAXParser().getXMLReader();

        xmlReader.parse(new InputSource(Files.newInputStream(path)));
    } catch (ParserConfigurationException | SAXException | IOException ex) {
        Logger.getLogger(SoftwareListLoader.class.getName()).log(Level.SEVERE, null, ex);
    }

我收到这个错误:

java.io.FileNotFoundException: F:\Project\softwarelist.dtd (Specified file not found)

有没有办法告诉解析器找到相对于 XML 文档文件的 dtd?

感谢 Google 和 O'Reilly,现在我明白发生了什么事了。

问题是我将 XML 文件作为流传递给解析器,这实际上会丢失对原始文件路径的任何引用。要解决此问题,有 2 个解决方案:

1/ 将原始文件路径设置为XML文档的System ID。

InputSource source = new InputSource(Files.newInputStream(path));
source.setSystemId(path.toString());
xmlReader.parse(source);

2/ 不走流

xmlReader.parse(new InputSource(path.toString()));

参考:http://docstore.mik.ua/orelly/xml/jxml/ch03_02.htm