用Java将表情符号写入XML文件 [英] Writing emoji to XML file in JAVA
本文介绍了用Java将表情符号写入XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
简短问题:给定String str = "😭";
输出包含<tag>😭</tag>
而不是<tag>😭</tag>
我正在尝试在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")));
推荐答案
默认情况下,emoji将被转换为其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?的答案。
这篇关于用Java将表情符号写入XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文