escapeXml
函数正在转换ѭ Ѯ
为ѭ Ѯ
我猜它不应该的。我读到的是它只支持五个基本的 XML 实体(gt
, lt
, quot
, amp
, apos
)。
有没有只转换这五个基本xml实体的函数?
escapeXml
函数正在转换ѭ Ѯ
为ѭ Ѯ
我猜它不应该的。我读到的是它只支持五个基本的 XML 实体(gt
, lt
, quot
, amp
, apos
)。
有没有只转换这五个基本xml实体的函数?
public String escapeXml(String s) {
return s.replaceAll("&", "&").replaceAll(">", ">").replaceAll("<", "<").replaceAll("\"", """).replaceAll("'", "'");
}
请注意,大于 0x7f 的 Unicode 字符从 3.0 开始,不再转义。如果您仍然希望使用此功能,可以通过以下方式实现: StringEscapeUtils.ESCAPE_XML.with( NumericEntityEscaper.between(0x7f, Integer.MAX_VALUE) );
因此,您可能使用的是旧版本的库。更新您的依赖项(或自己重新实现转义:这不是火箭科学)
的 javadocStringEscapeUtils.escapeXml
说我们必须使用
StringEscapeUtils.ESCAPE_XML.with( new UnicodeEscaper(Range.between(0x7f, Integer.MAX_VALUE)) );
但必须使用UnicodeEscaper
,代替。会将所有内容更改为符号,但转义为,这是预期的。NumericEntityEscaper
UnicodeEscaper
\u1234
NumericEntityEscaper
&#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 "; // the line cont
// no Unicode escape
final String escapedXml = StringEscapeUtils.escapeXml(xmlToEscape);
// escape Unicode as numeric codes. For instance, escape non-breaking space as  
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
}
}
在 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, """);
break;
case '&':
m.appendReplacement(buf, "&");
break;
case '\'':
m.appendReplacement(buf, "'");
break;
case '<':
m.appendReplacement(buf, "<");
break;
case '>':
m.appendReplacement(buf, ">");
break;
}
}
m.appendTail(buf);
return buf.toString();
}