我正在开发一个桌面应用程序,它使用 XPath 读取特定的 XML 元素并将它们显示在JFrame
.
到目前为止,程序运行顺利,直到我决定String
在类中传递一个变量File
。
public void openNewFile(String filePath) {
//file path C:\\Documents and Settings\\tanzim.hasan\\my documents\\xcbl.XML
//is passed as a string from another class.
String aPath = filePath;
//Path is printed on screen before entering the try & catch.
System.out.println("File Path Before Try & Catch: "+filePath);
try {
//The following statement works if the file path is manually written.
// File xmlFile = new File ("C:\\Documents and Settings\\tanzim.hasan\\my documents\\xcbl.XML");
//The following statement prints the actual path
File xmlFile = new File(aPath);
System.out.println("file =" + xmlFile);
//From here the document does not print the expected results.
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
XPath srcPath = XPathFactory.newInstance().newXPath();
XPathShipToAddress shipToPath = new XPathShipToAddress(srcPath, doc);
XPathBuyerPartyAddress buyerPartyPath = new XPathBuyerPartyAddress(srcPath, doc);
} catch (Exception e) {
//
}
}
如果我xmlFile
用静态路径定义(即手动编写),则程序按预期工作。但是,如果我将路径作为字符串变量传递,而不是编写静态路径,aPath
它不会打印预期的结果。
我做了一些谷歌搜索,但没有找到任何具体的东西。