Java从UTF-8中的URL读取XML?

时间:2019-01-28 16:21:02

标签: java xml utf-8

我正在尝试从URL解析XML数据,但由于从响应中读取¥字符时弄乱了它,因此似乎无法将它解析为UTF-8:

URL url = new URL("https://suggestqueries.google.com/complete/search?output=toolbar&hl=en&q=¥");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
final InputStream in = url.openStream();
final InputSource source = new InputSource(new InputStreamReader(in, "UTF-8"));
source.setEncoding("UTF-8");
Document doc = db.parse(source);
doc.getDocumentElement().normalize();

NodeList nodeList = doc.getElementsByTagName("suggestion");

for (int i = 0; i < 10; i++) {
    Node node = nodeList.item(i);
    if(node==null || listItems.size() > 10){
        break;
    }
    String suggestion = node.getAttributes().getNamedItem("data").getTextContent();
    // ...suggestions include � instead of ¥
}

source.setEncoding()在另一个线程中是一个可接受的答案,但似乎对我没有用。

1 个答案:

答案 0 :(得分:2)

似乎输入文件的编码不同于UTF-8。

这些对我有用:

阅读ISO-8859-1编码的文档

Document doc = db.parse(new InputSource(new InputStreamReader(url.openStream(), "ISO-8859-1")));

最终方法是:

URL url = new URL("https://suggestqueries.google.com/complete/search?output=toolbar&hl=en&q=¥");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new InputStreamReader(url.openStream(), "ISO-8859-1")));
doc.getDocumentElement().normalize();

NodeList nodeList = doc.getElementsByTagName("suggestion");

for (int i = 0; i < 10; i++) {
    Node node = nodeList.item(i);
    if(node==null){
        break;
    }
    String suggestion = node.getAttributes().getNamedItem("data").getTextContent();
    System.out.println(suggestion);
}