gpt4 book ai didi

java - xml 解析中的 UTF-8 问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:54:14 29 4
gpt4 key购买 nike

我正在使用以下代码将 XML 内容转换为 UTF-8,但它们无法正常工作:

1.

InputStream is = new ByteArrayInputStream(strXMLAlert.getBytes("UTF-8"));
Document doc = db.parse(is);

2.

InputSource is = new InputSource(new ByteArrayInputStream(strXMLAlert.getBytes()));
is.setCharacterStream(new StringReader(strXMLAlert));
is.setEncoding("UTF-8");
Document doc = db.parse(is);

最佳答案

我们可能需要更多信息才能正确回答问题。例如,您看到了什么问题?您运行的是哪个 Java 版本?

但是,将您的第一个示例扩展到

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
String strXMLAlert = "<a>永</a>";
InputStream is = new ByteArrayInputStream(strXMLAlert.getBytes("UTF-8"));
Document document = db.parse(is);
Node item = document.getDocumentElement().getChildNodes().item(0);
String nodeValue = item.getNodeValue();
System.out.println(nodeValue);

在这个例子中,字符串中有一个汉字。成功打印出来


尽管您提供了两次内容,但您的第二个示例也应该有效。要么将其作为一组字节提供并提供编码,要么仅将其作为字符(StringReader)提供并且您不需要编码(因为作为字符,它已经从字节解码为字符)。

关于java - xml 解析中的 UTF-8 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9696220/

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