【问题标题】:Invalid byte 2 of 2-byte UTF-8 sequence: XML saved as String varible2 字节 UTF-8 序列的无效字节 2:XML 保存为字符串变量
【发布时间】:2018-12-10 14:54:48
【问题描述】:

由于我的 XML 中的拉丁文本,我收到以下错误。

2 字节 UTF-8 序列的无效字节 2:XML 保存为字符串变量

我的 XML 被写入一个字符串变量(我不导入文件)。 我尝试将编码设置为“UTF-8”,但我可能做错了。

你能帮忙吗?

我的代码:

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputStream inputStream = new ByteArrayInputStream(GET_XML.getBytes());
Document doc = dBuilder.parse(inputStream);
doc.getDocumentElement().normalize();

【问题讨论】:

  • 欢迎来到 StackOverflow!您介意发布创建GET_XML 的代码吗?干杯:)

标签: java xml encode


【解决方案1】:

您看到此错误,因为您输入的 xml 包含 ISO-8859-1(又名 Latin-1)字符而没有正确的 XML 声明:

<?xml version='1.0' encoding='ISO-8859-1' standalone='no' ?>

您有两种选择,或者通过使用上述声明采购 xml 来纠正它。
在字节转换期间强制使用UTF-8

new ByteArrayInputStream(GET_XML.getBytes(StandardCharsets.UTF_8));

【讨论】:

    猜你喜欢
    • 2011-01-26
    • 1970-01-01
    • 2015-06-15
    • 2012-10-16
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多