[英]Java: JDOM2 write ascii character in xml
我正在使用JDOM2
編寫一個xml
客戶希望的是,有一條線如下:
<VT xml:space="preserve">20</VT>
但我能創造的是:
<VT xml:space="preserve">20</VT>
因為ascii是通過我的格式編碼轉換的(“ ISO-8859-1
”)
如何防止這個元素被轉換......?
這是我用的:
String str = "2";
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中,您可以建立規則來告訴輸出格式化程序何時轉義字符輸出。 這是非常不同尋常的,但你可以建立一個Escapetrategy,如:
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 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.