为了方便把map转换成了json字符串,单个数据用map封装,含层级的用list+map,使用递归可以完成多层数据的转换:
public static void main(String[] args) throws DocumentException {
String data = "<root>\n" +
" <time>20191011</time>\n" +
" <Service-Information>\n" +
" <Service-Result-Code>0</Service-Result-Code>\n" +
" <Para-Field-Result>用户无未打印发票信息!</Para-Field-Result>\n" +
" </Service-Information>\n" +
"</root>"; //xml格式的字符串
Map<String, Object> map = getDataDetail(data, "<root>"); //第二个字符串是从哪个位置截取需要的内容
String s = JSON.toJSONString(map);
System.out.println(s);
}
public static Map<String, Object> getDataDetail(String data,String str) throws DocumentException {
Map<String, Object> map = new HashMap<String, Object>();
int start = data.indexOf(str); //截取的起始位置
String endStr = str.replaceAll("<", "</");
int end = data.indexOf(endStr); //截取的重点位置
String sbData = data.substring(start, end + endStr.length()); // 截取到所需内容字符串
//String s = sbData.replaceAll("</Service-Information>|<Service-Information>", "");
Document doc = DocumentHelper.parseText(sbData); // 将字符串转为XML
Element rootElt = doc.getRootElement(); // 获取根节点
Iterator it = rootElt.elementIterator();
//List<List> recordDetaillist = new ArrayList<List>();
ArrayList<Map<String, Object>> arrayList= new ArrayList<Map<String, Object>>();
//String listName = "";
while (it.hasNext()) {
Element element = (Element) it.next();
map=test(element,map);
}
return map;
}
public static Map<String, Object> test(Element element,Map<String, Object> map){
//HashMap<String, Object> map = new HashMap<String, Object>();
boolean flg = false;
List<Element> list = element.elements();
if (list != null && list.size() == 0) {
map.put(element.getName(), element.getText()); //第一级
} else if (list != null && list.size() > 0) {
String listName = element.getName();
if (map.size()>=1){ //1.为了解决数据结构的问题,加个数据重名判断,并进行处理
Set<String> keySet = map.keySet();
flg = keySet.contains(listName);
}
ArrayList<Map<String, Object>> arrayList= new ArrayList<Map<String, Object>>(); //这里会出现数据结构单一,无法存在复数的map容器的问题
if (flg){ //重复的
arrayList=(ArrayList<Map<String, Object>>)map.get(listName); //把地址指向已有的容器
}
map.put(listName, arrayList); //确定容器
Map<String, Object> nextMap=new HashMap<String, Object>();//下一层的容器
//Map<String, Object> resultMap = new HashMap<String, Object>();
for (Element ee : list) {
//第二级
nextMap = test(ee,nextMap); //这里会出现地址值覆盖,思路是传一个map,返回值也用这个map
// resultMap.putAll(nextMap);
//hashMap.put(ee.getName(), ee.getText());
}
arrayList.add(nextMap);
}
return map;
}
控制台打印结果
{"Service-Information":[{"Para-Field-Result":"用户无未打印发票信息!","Service-Result-Code":"0"}],"time":"20191011"}
{
“Service-Information”: [{
“Para-Field-Result”: “用户无未打印发票信息!”,
“Service-Result-Code”: “0”
}],
“time”: “20191011”
}
如有什么不足和建议,请及时告知,好及时修改。
本文介绍如何将XML格式的字符串转换为Map对象。通过递归方法处理包含层级的数据,实现了多层数据的转化。示例展示了转换后的结果,包括'Service-Information'和'time'等关键数据。

3万+

被折叠的 条评论
为什么被折叠?



