无法使用JAVA从网站提取xml数据 [英] Unable to extract xml data from website using JAVA
本文介绍了无法使用JAVA从网站提取xml数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用JAVA在给定的经度和纬度下提取酒店名称的数据.我收到以下错误:[致命错误]:1:1:序言中不允许内容. 这是我尝试从中提取信息的代码和URL.关于这个问题有什么建议吗?
I'm trying to extract data for the hotel names at the given latitude and longitude in JAVA. I'm getting the following error: [Fatal Error] :1:1: Content is not allowed in prolog. Here is the code and the URL from where I am trying to extract my information. Any suggestion about the issue?
URL url = new URL("https://api.eancdn.com/ean-services/rs/hotel/v3/list?apiKey=vkndmgahz5aekd65pxg4rvvp&locale=en_US¤cyCode=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());
推荐答案
出了什么问题
如果运行以下代码,您将看到返回的数据不是XML,而是JSON.
What's Going Wrong
If you run the following code, you will see the data you are getting back is not XML, but 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¤cyCode=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格式请求数据:
Getting the Data as XML
You can use an HttpURLConnection
to request the data as 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¤cyCode=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);
}
}
这篇关于无法使用JAVA从网站提取xml数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文