1.问题
org.xhtmlrenderer.util.XRRuntimeException: Can’t load the XML resource (using TrAX transformer). org.xml.sax.SAXParseException; lineNumber: 84; columnNumber: 24; 对实体 “I” 的引用必须以 ‘;’ 分隔符结尾。
2.解决办法
原因是因为XML字符串内容"....店名 三十cafe&bar"里面包含了额外的“&”号,也需要转义
转义对照表:
https://bbs.huaweicloud.com/blogs/312362
编码实现:
/**
* 将字符串中的XML特殊字符转义
* & -> &
* < -> <
* > -> >
* " -> "
* ' -> '
* **/
public static String covertXML(String content) {
char[] originContentChars = content.toCharArray();
int finalContentCharLength = 0;//转义后字符串长度
for (char contentChar : originContentChars) {
switch (contentChar) {
case '&':
finalContentCharLength = finalContentCharLength + 5;
continue;
case '"':
case '\'':
finalContentCharLength = finalContentCharLength + 6;
continue;
case '<':
case '>':
finalContentCharLength = finalContentCharLength + 4;
continue;
default:
finalContentCharLength = finalContentCharLength + 1;
}
}
char[] newContentChars = new char[finalContentCharLength];
int newContentCharsPos = 0;
for (char originContentChar : originContentChars) {
switch (originContentChar) {
case '&':
//& -> &
newContentChars[newContentCharsPos] = '&';
newContentChars[newContentCharsPos + 1] = 'a';
newContentChars[newContentCharsPos + 2] = 'm';
newContentChars[newContentCharsPos + 3] = 'p';
newContentChars[newContentCharsPos + 4] = ';';
newContentCharsPos += 5;
continue;
case '"':
//" -> "
newContentChars[newContentCharsPos] = '&';
newContentChars[newContentCharsPos + 1] = 'q';
newContentChars[newContentCharsPos + 2] = 'u';
newContentChars[newContentCharsPos + 3] = 'o';
newContentChars[newContentCharsPos + 4] = 't';
newContentChars[newContentCharsPos + 5] = ';';
newContentCharsPos += 6;
continue;
case '\'':
//' -> '
newContentChars[newContentCharsPos] = '&';
newContentChars[newContentCharsPos + 1] = 'a';
newContentChars[newContentCharsPos + 2] = 'p';
newContentChars[newContentCharsPos + 3] = 'o';
newContentChars[newContentCharsPos + 4] = 's';
newContentChars[newContentCharsPos + 5] = ';';
newContentCharsPos += 6;
continue;
case '<':
//< -> <
newContentChars[newContentCharsPos] = '&';
newContentChars[newContentCharsPos + 1] = 'l';
newContentChars[newContentCharsPos + 2] = 't';
newContentChars[newContentCharsPos + 3] = ';';
newContentCharsPos += 4;
continue;
case '>':
//> -> >
newContentChars[newContentCharsPos] = '&';
newContentChars[newContentCharsPos + 1] = 'g';
newContentChars[newContentCharsPos + 2] = 't';
newContentChars[newContentCharsPos + 3] = ';';
newContentCharsPos += 4;
continue;
default:
newContentChars[newContentCharsPos] = originContentChar;
newContentCharsPos++;
}
}
return new String(newContentChars);
}
版权声明:本文为weixin_41926301原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。