简体   繁体   中英

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 ?

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" ?

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

xmlDocument.getDocumentURI();

Rather than creating a FileInputStream from the File and passing that to the parse method

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

use the version of parse that takes a File directly.

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

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() . Even if your XML doesn't actually use any namespaces, you still need to parse with a namespace-aware DOM parser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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