import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class XmlConvertToBean {
public static <T> T getDto(String xml,String startCompile,String endCompile,Class<T> c) {
T t = null;
try {
//开始的下标的KEY
String startKey = "startIndex";
//结束的下标的KEY
String endKey = "endIndex";
//正则匹配需要获取的开始的字符标记,截取字段如:<small hidden="">2</small>
Pattern startPattern = Pattern.compile(startCompile);
//正则匹配需要获取的结束的字符标记
Pattern endPattern = Pattern.compile(endCompile);
//开始标记对比
Matcher startMatcher = startPattern.matcher(xml);
//结束标记对比
Matcher endMatcher = endPattern.matcher(xml);
List<Map<String, Integer>> mapList = new ArrayList();
//开始标记查找
while (startMatcher.find() && endMatcher.find()) {
Map<String, Integer> map = new HashMap();
//<small hidden="">的结束下标
map.put(startKey, startMatcher.end());
//</small>的开始下标
map.put(endKey, endMatcher.start());
mapList.add(map);
}
for (int i = 0; i < mapList.size(); i++) {
Map<String, Integer> tempMap = mapList.get(i);
//根据前面获取的下标直接截取字段即可
xml = xml.substring(tempMap.get(startKey),
tempMap.get(endKey));
}
System.out.println("截取后-----"+xml);
t = converyToJavaBean(xml, c);
// System.out.println(dto1.getResponseCode());
// System.out.println(dto1.getOrderNo());
// System.out.println(dto1.getInsureCodeResultInfoList().get(0).getCodeName());
return t;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static <T> T converyToJavaBean(String xml, Class<T> c) {
T t = null;
try {
JAXBContext context = JAXBContext.newInstance(c);
Unmarshaller unmarshaller = context.createUnmarshaller();
t = (T) unmarshaller.unmarshal(new StringReader(xml));
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
}
xml转bean
最新推荐文章于 2023-11-15 14:07:06 发布