在ISO-8859-1编码的XML文档中解码Unicode字符

时间:2016-06-01 08:07:00

标签: java xml unicode iso-8859-1

使用javax.xml.transform我创建了这个ISO-8859-1文档,其中包含两个&##编码字符

<?xml version="1.0" encoding="ISO-8859-1"?>
<xml>&#50108; and &#50102;</xml>

问题:符合标准的XML阅读器如何解释쎼和쎶,

  • 就像普通&amp;#...字符串一样(未转换回

生成XML的代码:

public void testInvalidCharacter() {
    try {
        String str = "\uC3BC and \uC3B6"; // 쎼 and 쎶
        System.out.println(str);

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.newDocument();
        Element root = doc.createElement("xml");
        root.setTextContent(str);
        doc.appendChild(root);

        DOMSource domSource = new DOMSource(doc);

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.ISO_8859_1.name());

        StringWriter out = new StringWriter();
        transformer.transform(domSource, new StreamResult(out));

        System.out.println(out.toString());

    } catch (ParserConfigurationException | DOMException | IllegalArgumentException | TransformerException e) {
        e.printStackTrace(System.err);
    }
}

1 个答案:

答案 0 :(得分:1)

XML Parser将识别'&amp;#...'转义语法,并正确地返回쎼和쎶及其API元素的文本。 例如。在Java中,带有标记名称'xml'的Element的org.w3c.dom.Element.getTextContent()方法将返回带有Unicode字符的String,尽管您的XML文档本身是ISO-8859-1