如何将DOM文档对象转换为xml,应用utf-8字符集编码

时间:2016-03-21 17:52:13

标签: java xml encoding utf-8

我需要将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中的FILE下载组件,这里看到生成的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>

期望字符“¥©¢”被编码并显示为十六进制/八位字节代码。 有人可以建议这里出了什么问题吗?

1 个答案:

答案 0 :(得分:0)

您对UTF-8的理解不正确 - import html2text htmlconverter = html2text.HTML2Text() print htmlconverter.handle(''.join(name_tmp)) 已被编码为UTF-8以及文件的其余部分。您可以通过在十六进制编辑器中打开文件来验证,并找到序列:¥ © ¢,它将是'c2a5 c2a9 c2a2'的UTF-8编码。

AFAIK,你不应该在XML中使用十六进制/八进制字符转义序列。 XML解析器将解码您的文件而不会出现问题。

要测试代码是否适用于其他解析器,请使用以下python代码:

¥ © ¢