String msgXml = xml; String str = "<![CDATA[msgXml]]>";
如果xml里面还含有CDATA,xml解析str肯定会出错,因为CDATA是不能嵌套的。
我的解决方法就是把str 分成三部分,分别用3个CDATA包装,这样就不存在嵌套问题了,
下面是实现代码:
/** * 字符串帮助类 * @author * */ public class StringHelper { /** * <?xml version="1.0" encoding="UTF-8"?> <xxx Version="2.0" Type="xxxx" ToType = "3" ToID ="2384610" WSID="1966731" SoftVersion="1.0.1"> <xxxxx Version="2.0" SenderDevice="MP" RecieverDevice="" SenderID="49"> <Text Time="2014-09-29 10:58:05"><Content><![CDATA[fff]]></Content></Text> <Face Time="2014-09-29 10:58:05"><Content><![CDATA[emoji017]]></Content></Face> <Face Time="2014-09-29 10:58:05"><Content><![CDATA[emoji010]]></Content></Face> <Face Time="2014-09-29 10:58:05"><Content><![CDATA[emoji018]]></Content></Face> <Face Time="2014-09-29 10:58:05"><Content><![CDATA[emoji018]]></Content></Face> </xxxxx></xxx> */ /** * 格式化聊天消息xml -----]]><![CDATA[000000000003]]><![CDATA[----- * (CDATA不能嵌套,所以要格式化。用于保存聊天消息) * * @param xml * @return */ public static String formatMsgXml(String xml){ //首+:<Content>]]> //尾+:<![CDATA[</Content> String result = ""; String[] list = xml.split("<Content>"); for (int i = 0; i < list.length; i++) { if(i !=0){ if(i == 1){//首 list[i] = "<Content>]]>"+list[i]; }else{ list[i] = "<Content>"+list[i]; } if(i == (list.length-1)){//尾 String[] list2 = list[i].split("</Content>"); list2[1] = "<![CDATA[</Content>"+list2[1]; String end = ""; for (int j = 0; j < list2.length; j++) { end += list2[j]; } list[i] = end; } } System.out.println(list[i]); System.out.println("-------------------\r\n"); result += list[i]; } // System.out.println(result); return result; } }原文链接:https://www.f2er.com/xml/297861.html