gpt4 book ai didi

java - 转换 XML 不起作用 UTF-8 XMLOutputter Java

转载 作者:行者123 更新时间:2023-12-02 10:12:14 31 4
gpt4 key购买 nike

我已经看到了有关同一问题的其他问题,但我仍然收到错误。 Hier 是我尝试修改 exosting xml 文件的一小部分代码。但它修改了文本中的一些字符。

import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import java.io.FileOutputStream;
import java.io.IOException;

public class ModyfyXml {

public static void main(String[] args) throws JDOMException, IOException {

try {

SAXBuilder sax = new SAXBuilder();
Document doc = sax.build("F:\\c\\test.xml");

XMLOutputter xmlOutput = new XMLOutputter();
Format format = Format.getPrettyFormat();
format.setEncoding("UTF-8");
xmlOutput.setFormat(format);
xmlOutput.output(doc, (new FileOutputStream("F:\\c\\test2.xml")));

}catch (IOException io) {
io.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
}
}}

Hier 一个我尝试修改的小 xml 文件(在本例中只是复制)

<?xml version="1.0" encoding="utf-8"?><page>
䕶法喇嘛所居此處𡸁仲無妻室亦降神附體
</page>

程序启动后,我得到以下信息:

<?xml version="1.0" encoding="UTF-8"?>
<page>䕶法喇嘛所居此處&#x21e01;仲無妻室亦降神附體</page>

部分汉字无法正确转换

最佳答案

我从来没有注意到 JDOM 2 中的这个错误。

使用任何非 BMP 字符都会得到相同的结果。您可以尝试一下最近几年的表情符号热潮,看看您会得到相同的结果。

发生这种情况是因为自动为 UTF-whatever 编码设置了转义策略。它的做法是相当错误的。

如果您将该策略替换为不转义除 XML 保留字符之外的任何内容的策略,则该问题将得到解决:

format.setEscapeStrategy((c) -> false);

关于java - 转换 XML 不起作用 UTF-8 XMLOutputter Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54920849/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com