【问题标题】:Java Parsing xml document from urlJava从url解析xml文档
【发布时间】:2018-12-18 15:37:47
【问题描述】:

解析 URL 时,出现以下错误:

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

代码中应该改进什么? 还有必填链接。

    import org.w3c.dom.Document;
    import org.xml.sax.SAXException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;

    public class Main2 {
    public static void main(String[] args) throws ParserConfigurationException, MalformedURLException {
        String link = "https://samples.openweathermap.org/data/2.5/weather?q=London&appid=b6907d289e10d714a6e88b30761fae22";
        URL url = new URL(link);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        Document doc;
        try {
            builder = factory.newDocumentBuilder();
            doc =  builder.parse(url.openStream());
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            ex.printStackTrace();
        }
    }
}

【问题讨论】:

  • 为什么你认为那个 URL 会给你 XML?
  • 通过你的网址我看到的是 JSON,而不是 XML
  • 我 edited your question,改进其格式,或 its quality 以帮助人们理解您的问题,并帮助您获得适当的答案。但您仍可能需要添加更多信息才能让您的问题完全得到解决。

标签: java xml parsing url


【解决方案1】:

请您检查您提供的 URL 的确切响应类型,因为我在浏览器和邮递员中看到 Json 响应类型,即使我将内容类型发送为“application/xml”。所以不要使用 xml 解析器解析响应,因为您的响应是 JSON 格式的。您需要使用 json 解析器来解析 Json 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 2014-01-11
    • 2020-07-10
    • 1970-01-01
    相关资源
    最近更新 更多