6

escapeXml函数正在转换ѭ Ѯѭ Ѯ我猜它不应该的。我读到的是它只支持五个基本的 XML 实体(gt, lt, quot, amp, apos)。

有没有只转换这五个基本xml实体的函数?

4

4 回答 4

15
public String escapeXml(String s) {
    return s.replaceAll("&", "&amp;").replaceAll(">", "&gt;").replaceAll("<", "&lt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
}
于 2012-01-24T10:08:53.593 回答
7

库的 3.1 版本的 javadoc说:

请注意,大于 0x7f 的 Unicode 字符从 3.0 开始,不再转义。如果您仍然希望使用此功能,可以通过以下方式实现: StringEscapeUtils.ESCAPE_XML.with( NumericEntityEscaper.between(0x7f, Integer.MAX_VALUE) );

因此,您可能使用的是旧版本的库。更新您的依赖项(或自己重新实现转义:这不是火箭科学)

于 2012-01-24T10:12:28.750 回答
2

的 javadocStringEscapeUtils.escapeXml说我们必须使用

StringEscapeUtils.ESCAPE_XML.with( new UnicodeEscaper(Range.between(0x7f, Integer.MAX_VALUE)) );

但必须使用UnicodeEscaper,代替。会将所有内容更改为符号,但转义为,这是预期的。NumericEntityEscaperUnicodeEscaper\u1234NumericEntityEscaper&amp;#123;

package mypackage;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.text.translate.CharSequenceTranslator;
import org.apache.commons.lang3.text.translate.NumericEntityEscaper;

public class XmlEscaper {
    public static void main(final String[] args) {
        final String xmlToEscape = "<hello>Hi</hello>" + "_ _" + "__ __"  + "___ ___" + "after &nbsp;"; // the line cont

        // no Unicode escape
        final String escapedXml = StringEscapeUtils.escapeXml(xmlToEscape);

        // escape Unicode as numeric codes. For instance, escape non-breaking space as &#160;
        final CharSequenceTranslator translator = StringEscapeUtils.ESCAPE_XML.with( NumericEntityEscaper.between(0x7f, Integer.MAX_VALUE) );
        final String escapedXmlWithUnicode = translator.translate(xmlToEscape);

        System.out.println("xmlToEscape: " + xmlToEscape);
        System.out.println("escapedXml: " + escapedXml); // does not escape Unicode characters like non-breaking space
        System.out.println("escapedXml with unicode: " + escapedXmlWithUnicode); // escapes Unicode characters
    }
}
于 2017-09-11T16:48:42.680 回答
1

在 UTF-8 时代,有时首选具有可读字符的 XML 文档。这应该有效,并且唯一的重组String发生一次。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

private static final Pattern ESCAPE_XML_CHARS = Pattern.compile("[\"&'<>]");

public static String escapeXml(String s) {
    Matcher m = ESCAPE_XML_CHARS.matcher(s);
    StringBuffer buf = new StringBuffer();
    while (m.find()) {
        switch (m.group().codePointAt(0)) {
            case '"':
                m.appendReplacement(buf, "&quot;");
            break;
            case '&':
                m.appendReplacement(buf, "&amp;");
            break;
            case '\'':
                m.appendReplacement(buf, "&apos;");
            break;
            case '<':
                m.appendReplacement(buf, "&lt;");
            break;
            case '>':
                m.appendReplacement(buf, "&gt;");
            break;
        }
    }
    m.appendTail(buf);
    return buf.toString();
}
于 2015-03-06T09:25:26.410 回答