简体   繁体   English

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

[英]File-path from xPath-Object or Document-Object in Java

Is there a way to get the path of a XML-Document from a xPath- or Document-Object in the xPath-API ? 有没有一种方法可以从xPath-API中的xPath-或Document-Object获取XML文档的路径?

That´s how the Objects are initalized: 这就是对象的初始化方式:

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

So the question is: 所以问题是:

Could the Objects xmlDocument or xpath somehow return "C:\\ExampleFile.xml" ? 对象xmlDocumentxpath是否可以以某种方式返回"C:\\ExampleFile.xml"

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

xmlDocument.getDocumentURI();

Rather than creating a FileInputStream from the File and passing that to the parse method 而不是从File创建FileInputStream并将其传递给parse方法

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

use the version of parse that takes a File directly. 使用直接采用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

When you pass just a stream the parser has no way of knowing that that stream was created from a file, as far as the parser is concerned that could be a stream you received from a web server, or a ByteArrayInputStream , or some other non-file source. 当您仅传递流时,解析器无法得知该流是从文件创建的,就解析器而言,它可能是您从Web服务器, ByteArrayInputStream或其他一些非流接收到的流。文件源。 If you pass the File directly to parse then the parser will handle opening and closing the streams itself, and will be able to provide a meaningful URI to downstream components, and you'll get a sensible result from xmlDocument.getDocumentURI() . 如果直接传递File进行parse则解析器将自行处理流的打开和关闭,并且能够为下游组件提供有意义的URI,并且您将从xmlDocument.getDocumentURI()获得有意义的结果。

As an aside, if you want XPath to work reliably then you need to enable namespaces by calling builderFactory.setNamespaceAware(true) before you call newDocumentBuilder() . 顺便说一句,如果你想的XPath可靠地工作,那么你需要通过调用启用的命名空间builderFactory.setNamespaceAware(true)打电话之前newDocumentBuilder() Even if your XML doesn't actually use any namespaces, you still need to parse with a namespace-aware DOM parser. 即使您的XML实际上并未使用任何名称空间,您仍然需要使用可识别名称空间的DOM解析器进行解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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