gpt4 book ai didi

java - 使用标准 openStream 和 DocumentBuilder 的 utf-8

转载 作者:太空宇宙 更新时间:2023-11-04 14:35:51 24 4
gpt4 key购买 nike

需要将输出格式转换为UTF-8,因为输出不处理特殊字符。
有人知道如何做到这一点吗?

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
URL u = new URL("http://www.aredacao.com.br/tv-saude");
Document doc = builder.parse(u.openStream());
NodeList nodes = doc.getElementsByTagName("item");`

最佳答案

问题是网站返回 <?xml version='1.0' encoding='iso-8859-1'?>但它应该返回 <?xml version='1.0' encoding='UTF-8'?> .

一种解决方案是自己翻译每个元素的文本:

static void readData()
throws IOException,
ParserConfigurationException,
SAXException {

DocumentBuilder builder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
URL u = new URL("http://www.aredacao.com.br/tv-saude");
Document doc = builder.parse(u.toString());
NodeList nodes = doc.getElementsByTagName("item");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
Element el = (Element) node;

String title =
el.getElementsByTagName("title").item(0).getTextContent();
title = treatCharsAsUtf8Bytes(title);

String description =
el.getElementsByTagName("description").item(0).getTextContent();
description = treatCharsAsUtf8Bytes(description);

System.out.println("title=" + title);
System.out.println("description=" + description);
System.out.println();
}
}

private static String treatCharsAsUtf8Bytes(String s) {
byte[] bytes = s.getBytes(StandardCharsets.ISO_8859_1);
return new String(bytes, StandardCharsets.UTF_8);
}

另一种可能性是编写 FilterInputStream 的子类来替换错误的 <?xml prolog 的编码,但这需要更多的工作,并且只有当文档具有包含许多不同元素的复杂结构时我才会考虑这样做,这样翻译每个元素都会很麻烦。

关于java - 使用标准 openStream 和 DocumentBuilder 的 utf-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25592622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com