我需要将 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);
从上述代码中获得的输出流被提供给 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>
期望字符“¥ © ¢ ”已被编码并显示为十六进制/八位字节代码。 有人可以建议这里出了什么问题吗?
最佳答案
您对 UTF-8 的理解不正确 - ¥ © ¢
已与文件的其余部分一起编码为 UTF-8。您可以通过在十六进制编辑器中打开文件并找到序列来验证这一点:'c2a5 c2a9 c2a2'
,这将是 ¥ © cent
的 UTF-8 编码。
据我所知,您不应该在 XML 中使用十六进制/八进制字符转义序列。 XML 解析器将毫无问题地解码您的文件。
要测试您的代码是否可以与另一个解析器配合使用,请使用以下 python 代码:
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
print ET.tostring(root, encoding="UTF-8")
关于java - 如何应用 utf-8 字符集编码将 DOM 文档对象转换为 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36138267/