小编典典

无法使用JAVA从网站提取xml数据

java

我正在尝试在JAVA中以给定的经度和纬度提取酒店名称的数据。我收到以下错误:[致命错误]:1:1:序言中不允许内容。这是我尝试从中提取信息的代码和URL。关于这个问题有什么建议吗?

              URL url = new URL("https://api.eancdn.com/ean-services/rs/hotel/v3/list?apiKey=vkndmgahz5aekd65pxg4rvvp&locale=en_US&currencyCode=USD&latitude=51.514&longitude=-0.269"");
              InputStream is = url.openStream();
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              DocumentBuilder db = dbf.newDocumentBuilder();
              Document doc = db.parse(is);

                NodeList itemList = 
                        doc.getElementsByTagName("HotelSummary");
                Node itemNode;
                Element itemElt;


                for(int k=0; k < itemList.getLength(); k++)
                {
                    itemNode = itemList.item(k);

                    if(itemNode.getNodeType() == Node.ELEMENT_NODE) {
                        itemElt = (Element) itemNode;
                        System.out.println("Hotel name: "+itemElt.getElementsByTagName("name").item(0).getTextContent());

阅读 208

收藏
2020-10-18

共1个答案

小编典典

出了什么问题

如果运行以下代码,您将看到返回的数据不是XML,而是JSON。

import java.net.URL;
import java.io.InputStream;

public class Demo {

    public static void main(String[] args) throws Exception {
        URL url = new URL("https://api.eancdn.com/ean-services/rs/hotel/v3/list?apiKey=vkndmgahz5aekd65pxg4rvvp&locale=en_US&currencyCode=USD&latitude=51.514&longitude=-0.269");
        InputStream is = url.openStream();

        int next = is.read();
        while(next != -1) {
            System.out.print((char) next);
            next = is.read();
        }
    }

}

以XML形式获取数据

您可以使用HttpURLConnection来将数据请求为XML:

import java.net.HttpURLConnection;
import java.net.URL;
import java.io.InputStream;
import javax.xml.parsers.*;
import org.w3c.dom.Document;

public class Demo {

    public static void main(String[] args) throws Exception {
        URL url = new URL("https://api.eancdn.com/ean-services/rs/hotel/v3/list?apiKey=vkndmgahz5aekd65pxg4rvvp&locale=en_US&currencyCode=USD&latitude=51.514&longitude=-0.269");

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/xml");
        InputStream is = connection.getInputStream();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(is);
    }

}
2020-10-18