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&amp;$3$4"得到的结果就是替换了<msg></msg>中的“&”为“&amp;”
         //由于每次只能替换掉一个“&”,所以循环执行替换,直到替换后与替换前的字符串相等。
         String str1 = "" ;
         while (!str2.equals(str1)){
             str1 = str2;
             str2 = str1.replaceAll( "(<msg>.*)(&(?!amp;))(.*</msg>)" , "$1&amp;$3" );
         }
         System.out.println( "firstly replace \"&\": " +str2);
         
         //替换“<”
         str1 = "" ;
         while (!str2.equals(str1)){
             str1 = str2;
             str2 = str1.replaceAll( "(<msg>.*)(<)(.*</msg>)" , "$1&lt;$3" );
         }
         System.out.println( "then replace \"<\": " +str2);
         
         //替换“<”
         str1 = "" ;
         while (!str2.equals(str1)){
             str1 = str2;
             str2 = str1.replaceAll( "(<msg>.*)(>)(.*</msg>)" , "$1&gt;$3" );
         }
         System.out.println( "finally replace \">\": " +str2);
     }

 

 

感谢

http://my.oschina.net/u/178218/blog/55293 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值