【问题标题】:How to open a XML doc in Java如何在 Java 中打开 XML 文档
【发布时间】:2020-05-17 21:13:27
【问题描述】:

所以,我正在尝试使用 docBuilder.parse(filepath) 用 java 打开一个 XML 文档

这是我的代码的样子:

    public void openXMLfile(String filepath) {
        try { 
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(filepath);
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

我已经写了我的文件的绝对路径是:

C:\\Users\\"my User account"\\Desktop,是“我的用户帐户”,替换为我的用户帐户的实际名称

在我的 main 函数中,如下所示:

    public static void main(String[] args) {

        App aplication = new App();

        String filepath = "C:\\Users\\"my User account"\\Desktop";
        aplicacao.openXMLfile(filepath);
    }

但是,我得到以下错误:

java.net.MalformedURLException: unknown protocol: c
    at java.net.URL.<init>(Unknown Source)
    at java.net.URL.<init>(Unknown Source)
    at java.net.URL.<init>(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
    at Trabalho.App.openXMLfile(App.java:39)
    at Trabalho.App.main(App.java:70)

谁能澄清我可能做错了什么?可能是文件路径本身吗?

非常感谢您!

【问题讨论】:

  • 不是 100% 所以不作为答案,但错误提示您需要 file:// 前缀
  • 不确定是否需要像 windows 一样的反斜杠 - file://c/account/ 等可能会起作用

标签: java xml file dom path


【解决方案1】:

parse 方法采用文件位置的 URI,因此类似于 file:///c:/user/

这个问题给出了例子 - How should a file: URI corresponding to a Windows path name look like? 特别是保罗的评论。

示例也在https://en.m.wikipedia.org/wiki/File_URI_scheme

【讨论】:

  • 为我修复了它。只需在文件路径后面添加“file:///”,就可以了。谢谢克里斯 :)
  • 太棒了 - 像这样的小事情可能需要最长时间才能弄清楚!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-19
  • 1970-01-01
  • 2011-03-03
  • 1970-01-01
  • 2018-12-11
  • 2019-01-28
  • 1970-01-01
相关资源
最近更新 更多