Java:JDOM2在xml中写入ascii字符

标签 java xml ascii jdom-2

我正在使用 JDOM2 编写 xml

客户希望有一行如下:

<VT xml:space="preserve">&#50;&#48;</VT>

但我能创造的是:

<VT xml:space="preserve">20</VT>

因为ascii是通过我的格式编码转换的(“ISO-8859-1”)

如何防止该元素被转换...?

这是我使用的:

String str = "&#50;";
String unescapeXml = StringEscapeUtils.unescapeXml(str);
element.addContent(unescapeXml);

我也用:

format = Format.getPrettyFormat();
format.setEncoding("ISO-8859-1");
format.setExpandEmptyElements(true);
XMLOutputter out;
OutputStreamWriter fw = null;

out = new XMLOutputter();
out.setFormat(format);

try {
    fw = new OutputStreamWriter(new FileOutputStream(file));
    PrintStream printStream = System.out;

    // fw = new FileWriter(file);

    out.output(doc, printStream);

最佳答案

在 JDOM 中,您可以建立规则来告诉输出格式化程序何时转义字符输出。这是非常非常规的,但你可能可以构建一个逃避策略,例如:

private static final EscapeStrategy alldigits = new EscapeStrategy() {
    @Override
    public boolean shouldEscape(char ch) {
        return Character.isDigit(ch) || DefaultEscapeStrategy.shouldEscape(ch);
    }
};

上述实例将导致所有数字和任何其他常规转义字符被转义。

然后您可以在输出格式化程序的实例上设置该策略:

format = Format.getPrettyFormat();
format.setEncoding("ISO-8859-1");
format.setExpandEmptyElements(true);
format.setEscapeStrategy(alldigits);

在此处阅读有关 EscapeStrategy 的更多信息:http://jdom.org/docs/apidocs/org/jdom2/output/EscapeStrategy.html

以及它在 JDOM 中的使用方式:https://github.com/hunterhacker/jdom/blob/master/core/src/java/org/jdom2/output/Format.java#L147在这里:https://github.com/hunterhacker/jdom/blob/master/core/src/java/org/jdom2/output/support/AbstractXMLOutputProcessor.java#L765

关于Java:JDOM2在xml中写入ascii字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41719373/

相关文章:

java - 如何知道表情符号的ASCII/UTF编码?

C#:XML 转换

iphone - 用于 iPhone 的 Objective-C DOM XML 解析器

Python XML 解析、lxml、urllib.request

python - 如何获得将非 ASCII 字符识别为字母的正则表达式?

java - 在Java中输入数组最有效的方法是什么?

java - 从java在远程linux中运行命令

Java:将参数传递给有界参数函数

java - 使用编译时环境变量配置 RestApplicationPath

c# - 初学者角色扮演游戏碰撞检测