使用 dom4j 读取时转换文档编码

发布于 2024-07-23 12:21:41 字数 202 浏览 4 评论 0原文

有什么方法可以将 dom4j 的 SAXReader 解析的文档从 ISO-8859-2 编码转换为 UTF-8 吗? 我需要在解析时发生这种情况,以便 dom4j 创建的对象已经是 Unicode/UTF-8 并运行如下代码:

"some text".equals(node.getText());

返回 true。

Is there any way I can convert a document being parsed by dom4j's SAXReader from the ISO-8859-2 encoding to UTF-8? I need that to happen while parsing, so that the objects created by dom4j are already Unicode/UTF-8 and running code such as:

"some text".equals(node.getText());

returns true.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

长梦不多时 2024-07-30 12:21:41

这是由 dom4j 自动完成的。 Java 中的所有 String 实例都采用通用的解码形式; 一旦创建了String,就不可能知道原始字符编码是什么(或者即使字符串是从编码字节创建的)。

只需确保 XML 文档指定了字符编码(除非是 UTF-8,否则这是必需的)。

This is done automatically by dom4j. All String instances in Java are in a common, decoded form; once a String is created, it isn't possible to tell what the original character encoding was (or even if the string was created from encoded bytes).

Just make sure that the XML document has the character encoding specified (which is required unless it is UTF-8).

薄情伤 2024-07-30 12:21:41

解码发生在 InputSource 中(或之前)(在 SAXReader 之前)。 从该类的 javadoc 中:

SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入。 如果有可用的字符流,解析器将直接读取该流,而忽略该流中找到的任何文本编码声明。 如果没有字符流,但有字节流,则解析器将使用该字节流,使用 InputSource 中指定的编码,否则(如果未指定编码)使用算法自动检测字符编码,例如XML 规范。 如果字符流和字节流都不可用,解析器将尝试打开与系统标识符标识的资源的 URI 连接。

所以这取决于您如何创建InputSource。 为了保证正确的解码,您可以使用如下所示的内容:

InputStream stream = <input source>
Charset charset = Charset.forName("ISO-8859-2");
Reader reader = new BufferedReader(new InputStreamReader(stream, charset));
InputSource source = new InputSource(reader);

The decoding happens in (or before) the InputSource (before the SAXReader). From that class's javadocs:

The SAX parser will use the InputSource object to determine how to read XML input. If there is a character stream available, the parser will read that stream directly, disregarding any text encoding declaration found in that stream. If there is no character stream, but there is a byte stream, the parser will use that byte stream, using the encoding specified in the InputSource or else (if no encoding is specified) autodetecting the character encoding using an algorithm such as the one in the XML specification. If neither a character stream nor a byte stream is available, the parser will attempt to open a URI connection to the resource identified by the system identifier.

So it depends on how you are creating the InputSource. To guarantee the proper decoding you can use something like the following:

InputStream stream = <input source>
Charset charset = Charset.forName("ISO-8859-2");
Reader reader = new BufferedReader(new InputStreamReader(stream, charset));
InputSource source = new InputSource(reader);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文