字符串的截取处理
有时候需要处理xml格式的报文,修改其中的数据,可以用到以下 的方法:
/** * 生成head报文 * * @param headParams * @return String */ protected String getGWHead(Context context, List<String> headParams) throws EMPException { StringBuffer result = new StringBuffer(); result.append("<"+SEND_HEAD_ROOT_TAG_NAME+">"); if (headParams != null) { for (int i = 0; i < headParams.size(); i++) { String param = (String) headParams.get(i); String[] paramArray = param.split(","); String field = paramArray[0]; String value = paramArray[1]; result.append("<").append(field).append(">").append(value).append("</").append(field).append(">"); } } result.append("</"+SEND_HEAD_ROOT_TAG_NAME+">"); return result.toString(); }
/** * 添加标签List下内容 * @param message 报文内容 * @param tagName 标签名 * @return */ private String setTextListContent(String message, String tagName ) { String tagBegin="<"+tagName+">"; String tagEnd="</"+tagName+">"; int tagBeginPos = message.indexOf( tagBegin ); int tagEndPos = message.lastIndexOf(tagEnd) + tagEnd.length(); if ( tagBeginPos >= 0 ) { String text=message.substring(0, message.indexOf("<"+tagName+">"));//+("</"+tagName+">").length() 获取字符串前边内容 message.indexOf("<"+SEND_BODY_ROOT_TAG_NAME+">") StringBuffer pub=new StringBuffer(); pub.append(text); //替换List的内容 pub.append("<m>"); String mid = message.substring(tagBeginPos, tagEndPos); pub.append(mid); pub.append("</m></response></"+SEND_BODY_ROOT_TAG_NAME+">"); return pub.toString(); } // int tagBeginPos = message.indexOf( tagBegin ); // if ( tagBeginPos >= 0 ) // { // tagBeginPos=tagBeginPos+tagBegin.length(); // int tagEndPos = message.lastIndexOf(tagEnd); // return message.substring(tagBeginPos, tagEndPos); // } return ""; }