为了方便把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<