当前位置: 代码迷 >> java >> Java中xPath对象或Document对象的文件路径
  详细解决方案

Java中xPath对象或Document对象的文件路径

热度:87   发布时间:2023-07-31 10:55:53.0

有没有一种方法可以从xPath-API中的xPath-或Document-Object获取XML文档的路径?

这就是对象的初始化方式:

FileInputStream file = new FileInputStream(new File("C:\ExampleFile.xml"));

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 

DocumentBuilder builder =  builderFactory.newDocumentBuilder();                          

Document xmlDocument = builder.parse(file);

XPath xPath =  XPathFactory.newInstance().newXPath();

所以问题是:

对象xmlDocumentxpath是否可以以某种方式返回"C:\\ExampleFile.xml"

使用Document对象xmlDocument可以使用以下命令返回文件的路径:

xmlDocument.getDocumentURI();

而不是从File创建FileInputStream并将其传递给parse方法

FileInputStream file = new FileInputStream(new File("C:\\ExampleFile.xml"));

使用直接采用Fileparse版本。

File file = new File("C:\\ExampleFile.xml");
// rest of your code is unchanged - parse(file) is now the
// java.io.File version rather than the InputStream version

当您仅传递流时,解析器无法得知该流是从文件创建的,就解析器而言,它可能是您从Web服务器, ByteArrayInputStream或其他一些非流接收到的流。文件源。 如果直接传递File进行parse则解析器将自行处理流的打开和关闭,并且能够为下游组件提供有意义的URI,并且您将从xmlDocument.getDocumentURI()获得有意义的结果。

顺便说一句,如果你想的XPath可靠地工作,那么你需要通过调用启用的命名空间builderFactory.setNamespaceAware(true)打电话之前newDocumentBuilder() 即使您的XML实际上并未使用任何名称空间,您仍然需要使用可识别名称空间的DOM解析器进行解析。