XML UTF-8 JAXB 编组后内容仍为 ISO 8859-1

XML content still ISO 8859-1 after UTF-8 JAXB Marshalling

我正在使用 camel 创建一个 JAXB 对象,对其进行编组,然后将结果写入 UTF-8 编码的 XML 文件中。 我的一些 xml 内容是从使用 ISO 8859-1 编码的数据源中获取的:

这是我的骆驼路线:

import org.apache.camel.converter.jaxb.JaxbDataFormat;

JaxbDataFormat jaxbDataFormat = new JaxbDataFormat(Claz.class.getPackage().getName());

from("endpoint")

   .process(//createObjectBySettingTheDataFromSource)

   .marshal(jaxbDataFormat)

   .to(FILEENDPOINT?charset=utf-8&fileName=" +Filename);

XML生成成功,但从源头抓取的数据内容仍然是ISO编码,没有用UTF8解析。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>     
     <Name>M��e Faࠥnder</Name> //Mürthe Faßender 

通过将文件编码更改为 ISO 8859-1,内容已成功解析。

我尝试在将数据设置到 JAXB 对象之前转换数据,但仍未在 UTF-8 中解析。

  byte[] nameBytes = name.getBytes(StandardCharsets.ISO_8859_1);
  return new String(nameBytes, StandardCharsets.UTF_8);

问题仅在 Linux 下出现,有没有人知道如何操作 ISO_8859_1 数据并在 xml 中毫无问题地设置它?

嗯,UTF-8 是默认字符集(至少对于文件端点而言)并且 AFAIK Camel 不会尝试分析输入消息的给定字符集。

所以我想如果你不声明不同于 UTF-8 的输入字符集,然后将文件写成 UTF-8,那么 no需要从骆驼的角度转换任何东西。

.from("file:inbox") // implicit UTF-8
.to("file:outbox?charset=utf-8") // same charset, no conversion needed

至少对于文件,您可以声明源编码,以便 Camel 知道它必须转换有效负载。

.from("file:inbox?charset=iso-8859-1") 
.to("file:outbox?charset=utf-8") // conversion needed

如果您无法声明输入字符集(我认为这取决于端点类型),则必须显式转换有效负载。

.from("file:inbox") 
.convertBodyTo(byte[].class, "utf-8")
// message body is now a byte array and written to file as is
.to("file:outbox") 

有关详细信息,请参阅 Camel File docs 中的 "Using charset" 部分。