Java читает XML из URL в UTF-8? - PullRequest
0 голосов
/ 28 января 2019

Я пытаюсь проанализировать данные XML с URL-адреса, но не могу получить их для анализа как 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 голосов
/ 28 января 2019

Кажется, что кодировка входного файла отличается от 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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...