我需要将DOM文档对象转换为xml,并确保xml的内容是utf-8字符集。我的代码看起来像下面这样,但是它没有达到预期的结果,并且在生成的xml中,我可以看到字符没有编码。
Document doc = (Document)operation.getResult(); //this method is returning the document object
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
DOMSource domSource = new DOMSource(doc);
OutputStreamWriter osw = new OutputStreamWriter(outputStream, "UTF-8");
StreamResult result = new StreamResult(osw);
transformer.transform(domSource,result);从上面的代码中获得的outputStream被提供给ADF中的一个文件下载组件,在这里,由于生成的xml文件没有针对特殊字符进行编码,因此生成了标头行,说明编码正在生成。生成的xml文件示例如下所示。
<?xml version = '1.0' encoding = 'UTF-8'?>
<PlanObjects>
<CompPlan BusinessUnit="Vision Operations" OrgId="204" Name="RNNewCompPlan" StartDate="2015-01-01" EndDate="2015-12-31">
<CompPlansVORow>
<CompPlanName>RNNewCompPlan</CompPlanName>
<Description>Using some special chars in desc - ¥ © ¢ </Description>
<DisplayName>RNNewCompPlan</DisplayName>
</CompPlansVORow>
</CompPlan>
</PlanObjects>预期字符“元©”已被编码并显示为十六进制/八位字节代码。有人能建议一下这里出了什么问题吗?
发布于 2016-03-22 16:49:03
您对UTF-8的理解是错误的- ¥ © ¢已被编码为UTF-8,以及文件的其余部分。您可以通过在十六进制编辑器中打开文件并找到序列:'c2a5 c2a9 c2a2'来验证这一点,这将是¥ © ¢的UTF8编码。
AFAIK,您不应该在XML中使用十六进制/八进制字符转义序列。XML解析器将不会出现问题地解码您的文件。
要测试您的代码是否能与另一个解析器一起工作,请使用以下python代码:
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
print ET.tostring(root, encoding="UTF-8")https://stackoverflow.com/questions/36138267
复制相似问题