这篇文章将为大家详细讲解有关xml型字符串解析时存在& < >符号时如何解决,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
问题产生:
在接口调用得出一个xml型字符串,一直报错
The entityname must immediately follow the '&' in the entity reference
经查发现 xml的内容里存在有 &符号 而 通过dom4j读取时 会发生错误
在xml中 “&”“<”“>”这样的标签存放在内容里是不合法的,会经常出问题。
下面找到解决方法:实测 替换 & 是可行的。
public void chartReplace(){
String str2 = "<logentry revision='1'>" +
"<msg>In this comment, I fixed a <bug>, and <added> file1&&file2.</msg>" +
"</logentry>";
System.out.println("original string: "+str2);
//替换“&”:$1表示与(<msg>.*)的匹配子序列;$4表示与(.*</msg>)匹配的。
//&(?!amp;)表示匹配&而且后面不是amp;的字符串
//"$1&$3$4"得到的结果就是替换了<msg></msg>中的“&”为“&”
//由于每次只能替换掉一个“&”,所以循环执行替换,直到替换后与替换前的字符串相等。
String str1 = "";
while(!str2.equals(str1)){
str1 = str2;
str2 = str1.replaceAll("(<msg>.*)(&(?!amp;))(.*</msg>)", "$1&$3");
}
System.out.println("firstly replace \"&\": "+str2);
//替换“<”
str1 = "";
while(!str2.equals(str1)){
str1 = str2;
str2 = str1.replaceAll("(<msg>.*)(<)(.*</msg>)", "$1<$3");
}
System.out.println("then replace \"<\": "+str2);
//替换“<”
str1 = "";
while(!str2.equals(str1)){
str1 = str2;
str2 = str1.replaceAll("(<msg>.*)(>)(.*</msg>)", "$1>$3");
}
System.out.println("finally replace \">\": "+str2);
}
关于xml型字符串解析时存在& < >符号时如何解决就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。