将表情符号写入 JAVA 中的 XML 文件

Writing emoji to XML file in JAVA

小问题:给定一个 String str = ""; 输出一个包含 <tag></tag> 而不是 <tag>&#128557;</tag>

的 XML 文件

我正在尝试在 JAVA 中创建一个 XML 文件,该文件可能在标签中包含普通文本或表情符号。 XML 文件采用 UTF-8 编码,因此在 Notepad++ 中打开时,您可以在标签中看到普通文本和表情符号。在测试我的代码时,表情符号以某种方式被翻译为 &#xxxxxx;.

示例代码:

String str = "";
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element root = document.createElement("tag");
root.appendChild(document.createTextNode(str));
document.appendChild(root);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(document), new StreamResult(new File("test.xml")));

默认情况下,表情符号将被翻译成它们的 HTML 代码,但您可以通过嵌入一条指令来禁用输出转义来防止这种情况。这是一个使用您的代码的示例,仅需要两行额外的代码来禁用转义,然后通过 calling the Document method createProcessingInstruction():

启用转义
package com.unthreading.emojitoxml;

import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.OutputKeys;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

public class App {

    public static void main(String[] args) throws ParserConfigurationException, TransformerException {

        String str = "";
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element root = document.createElement("tag");
        document.appendChild(document.createProcessingInstruction(StreamResult.PI_DISABLE_OUTPUT_ESCAPING, "")); // <=== ADD THIS LINE
        root.appendChild(document.createTextNode(str));
        document.appendChild(root);
        document.appendChild(document.createProcessingInstruction(StreamResult.PI_ENABLE_OUTPUT_ESCAPING, "")); // <=== ADD THIS LINE
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(new DOMSource(document), new StreamResult(new File("test.xml")));
    }
}

这是test.xml在运行那个代码之后的内容:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><tag></tag>

备注:

  • 传递给 document.createProcessingInstruction() 的第二个 String 参数似乎无关紧要。在我的示例中,我只传递了一个空字符串。
  • 查看 SO 问题 What is the use of static fields PI_ENABLE_OUTPUT_ESCAPING & PI_DISABLE_OUTPUT_ESCAPING and how can we use them? 的答案,了解有关使用此方法的可取性的更多信息。