【问题标题】:How to Read XML Document from URL如何从 URL 读取 XML 文档
【发布时间】:2014-03-18 18:05:49
【问题描述】:

您好,我正在使用文档类。当我从本地系统读取文件时它正在工作,当我想读取文件并尝试从某个 URL 加载 XML 文档时它不起作用。

private static Document loadTestDocument(String fileLocation) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder db = factory.newDocumentBuilder();
    File file = new File(fileLocation);
    System.out.println(db.parse(file).toString());
    return  db.parse(file);
}

因此,如果我有一个返回 xml 的服务并且我想使用它,那么这个方法将返回 Document 我该怎么做我想直接从服务 GET url 加载。

我试过了,但它不起作用

File file = new File("http://someservice/getdata");

错误:找不到文件 然后我尝试从输入流中加载它,它对我也不起作用。

InputStream input = new URL("http://someurl:32643/api/values").openStream();

错误:

[Fatal Error] :1:1: Content is not allowed in prolog.

现在我该如何实现这一点,任何帮助将不胜感激

【问题讨论】:

  • 您正在加载的文档是什么样的?
  • 我明白这一点。它看起来像什么。
  • 这对我也不起作用: DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder();文档 doc = db.parse(new URL("someehost:32643/api/values").openStream());
  • 类似这样:w3.org/2001/XMLSchema-instance" xmlns="schemas.microsoft.com/2003/10/Serialization/Arrays"> value1value2 ArrayOfstring>
  • 标题呢? <?xml version="1.0"?>你有吗?这很重要。这是你的prolog

标签: java jakarta-ee xml-parsing saxparser domparser


【解决方案1】:

以下代码适用于我。

TestXML.java

import java.net.URL;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

public class TestXML {

    private static Document loadTestDocument(String url) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        return factory.newDocumentBuilder().parse(new URL(url).openStream());
    }

    public static void main(String[] args) throws Exception {
        Document doc = loadTestDocument("http://www.enetpulse.com/wp-content/uploads/sample_xml_feed_enetpulse_soccer.xml");
        System.out.println(doc);
        doc = loadTestDocument("http://localhost/array.xml");
        System.out.println(doc);
    }
}

数组.xml

<?xml version="1.0"?>
<ArrayOfstring xmlns:i="w3.org/2001/XMLSchema-instance" xmlns="schemas.microsoft.com/2003/10/Serialization/Arrays">
    <string>value1</string> 
    <string>value2</string> 
</ArrayOfstring>

你真的需要/使用 xmlns 属性吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多