标签:start 表达 substring 次数 public 表达式 result ret 算子
直接贴代码上来吧,就是简单的正则表达式+搭配字符串查询解析
工具类函数
//获取 pattern1 与 pattern2 在src字符中 中间的部分字符串
public String getAttribute(String src,String pattern1,String pattern2){
String result = null;
int index1 = 0;
int index2 = 0;
index1 =src.indexOf(pattern1);
index2 = src.indexOf(pattern2);
result = src.substring(index1+pattern1.length()+9,index2-3);
return result;
}
// 获取第i次出现在string中的字符串str的开始位置
public static int getIndex(String string, int i, String str) {
Matcher slashMatcher = Pattern.compile(str).matcher(string);
int mIdx = 0;
while (slashMatcher.find()) {
mIdx++;
if (mIdx == i) {
break;
}
}
return slashMatcher.start();
}
//计算子串出现的次数
private int countStr(String str,String sToFind) {
int num = 0;
while (str.contains(sToFind)) {
str = str.substring(str.indexOf(sToFind) + sToFind.length());
num ++;
}
return num;
}
使用函数解析xml文件,这是xml文件省略了,re.getBody()返回的就是xml文件格式的字符串,解析的就是这个字符串。
String returnstr = "";
//存储ids.length条信息
String[] strs = new String[ids.length];
List<ItemVO> listVO = new ArrayList<ItemVO>();
for(int i=0;i<ids.length;i++){
String id = ids[i];
//根据Id获取item商品信息,其中包括
//商品ID 图片 商品名称 店铺名称 当当价库存 商品状态 审核状态 最后修改时间
ItemVO itemVO = new ItemVO();
//审核状态 和最后修改时间去ItemList获取
itemVO.setCheckstate(datatypeStrs[i]);
itemVO.setLastupdatetime(updatetimeStrs[i]);
itemVO.setStorename(storename);
//商品ID 图片 商品名称 店铺名称 价格,库存 商品状态 去Item接口获取
ItemGetRequest request = new ItemGetRequest();
ItemGet get = new ItemGet();
get.setIt(id);
request.setItemsGet(get);
ItemGetResponse re = sdkClient.excute(request);
//开始解析单个的商品
String itemInfoStr = re.getBody();
String itemId = getAttribute(itemInfoStr,"<itemID>","</itemID>");
itemVO.setStoreId(itemId);
String itemName = getAttribute(itemInfoStr,"<itemName>","</itemName>");
itemVO.setGoodsname(itemName);
String unitPrice =getAttribute(itemInfoStr,"<unitPrice>","</unitPrice>");
itemVO.setUnitPrice(unitPrice);
String stockCount = getAttribute(itemInfoStr,"<stockCount>","</stockCount>");
itemVO.setStockCount(stockCount);
String itemState = getAttribute(itemInfoStr,"<itemState>","</itemState>");
itemVO.setGoodstate(itemState);
//解析一下图片
int countpic = countStr(re.getBody(), "<pic");
String pistrs = "";
int[] beginpic = new int[countpic];
int[] endpic = new int[countpic];
for(int h=1;h<=countpic;h++){
beginpic[h-1] = getIndex(re.getBody(),h,"<pic");
endpic[h-1] = getIndex(re.getBody(),h,"</pic");
}
for(int j=0;j<countpic;j++){
int begin0 = beginpic[j];
int end0 = endpic[j];
pistrs += re.getBody().substring(begin0 + 15, end0 - 3);
}
itemVO.setPicture(pistrs);
if(i<ids.length-1)
returnstr+=itemVO.toString()+"#";
else
returnstr+=itemVO.toString();
}
为了解析这个xml格式字符串,还花了一个小时去分析一下,写的过程其实思路很简答,就是繁琐了一点。
标签:start 表达 substring 次数 public 表达式 result ret 算子
原文地址:https://www.cnblogs.com/Koaler/p/11996892.html