简体   繁体   English

Java:JDOM2在xml中编写ascii字符

[英]Java: JDOM2 write ascii character in xml

i am writing a xml, using JDOM2 我正在使用JDOM2编写一个xml

the customers wish is, to have a line as follows: 客户希望的是,有一条线如下:

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

but all I can create is: 但我能创造的是:

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

because the ascii is converted by my format encoding (" ISO-8859-1 ") 因为ascii是通过我的格式编码转换的(“ ISO-8859-1 ”)

how to prevent this element from being converted...? 如何防止这个元素被转换......?

this is, what i use: 这是我用的:

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

also i use: 我也用:

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);

In JDOM you can establish rules for telling the output formatter when to escape character output. 在JDOM中,您可以建立规则来告诉输出格式化程序何时转义字符输出。 It is highly unconventional, but you could probably build an Escapetrategy like: 这是非常不同寻常的,但你可以建立一个Escapetrategy,如:

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

The above instance will cause all digits, and any other regularly-escaped characters to be escaped. 上述实例将导致所有数字和任何其他常规转义字符被转义。

You can then set that strategy on an instance of your output formatter: 然后,您可以在输出格式化程序的实例上设置该策略:

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

Read up more about the EscapeStrategy here: http://jdom.org/docs/apidocs/org/jdom2/output/EscapeStrategy.html 阅读更多关于EscapeStrategy的信息: http ://jdom.org/docs/apidocs/org/jdom2/output/EscapeStrategy.html

and the way it is used in JDOM here: https://github.com/hunterhacker/jdom/blob/master/core/src/java/org/jdom2/output/Format.java#L147 and here: https://github.com/hunterhacker/jdom/blob/master/core/src/java/org/jdom2/output/support/AbstractXMLOutputProcessor.java#L765 以及它在JDOM中的使用方式: https: //github.com/hunterhacker/jdom/blob/master/core/src/java/org/jdom2/output/Format.java#L147 and here: https:// github.com/hunterhacker/jdom/blob/master/core/src/java/org/jdom2/output/support/AbstractXMLOutputProcessor.java#L765

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM