来源:http://itssh.cn/post/905.html
在日常开发中经常碰到xml解析,现提供递归解析xml类以供参考
package cn.sunmeng;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
* @ClassName: ParseXML
* @Description: 递归解析xml
* @author: SM(sm0210@qq.com)
*
*
* <?xml version="1.0" encoding="UTF-8"?>
<xml>
<CustList>
<TName>SMToUserName</TName>
<FName>SMFromUserName</FName>
<CTime>SMCreateTime1348831860</CTime>
<MType>SMMsgType</MType>
<Content>SMContent</Content>
<MId>SMMsgId1234567890123456</MId>
<SrcLabel>SMSrcLabel</SrcLabel>
<Code>00</Code>
</CustList>
<CustList>
<TName>2SMToUserName</TName>
<FName>2SMFromUserName</FName>
<CTime>2SMCreateTime1348831860</CTime>
<MType>2SMMsgType</MType>
<Content>2SMContent</Content>
<MId>2SMMsgId1234567890123456</MId>
<SrcLabel>2SMSrcLabel</SrcLabel>
<Code>200</Code>
<SMCust>
<SM1>sm1val</SM1>
<SM2>sm2val</SM2>
</SMCust>
<SMCust>
<SM1>sm3val</SM1>
<SM2>sm4val</SM2>
</SMCust>
</CustList>
<Code>1200</Code>
<Content>Success</Content>
</xml>
*
*/
public class ParseXML {
/**
* @FieldName: ARRAY_PROPERTY
* @FieldType: 数组节点
* @Description: 数组节点
*/
private static final List<String> ARRAY_PROPERTY = Arrays.asList(new String[]{"CustList","SMCust"});
/**
*
* @param xml
* @param config
* @return
* @throws Exception
*/
private Map<String, Object> parserXml(String xml) throws Exception {
StringReader reader = new StringReader(xml);
// 创建一个新的SAXBuilder
SAXReader sb = new SAXReader();
//
Map<String, Object> result = new HashMap<String, Object>();
//
try {
// 通过输入源构造一个Document
Document doc = sb.read(reader);
// 取的根元素
Element root = doc.getRootElement();
List children = root.elements();
//解析xml
result = toMap(children,null);
} catch (Exception e) {
System.err.print(e.getMessage());
throw e;
} finally {
if(reader != null) {
reader.close();
}
}
return result;
}
/**
* 递归解析xml,实现N层解析
* @param xml
*/
private Map<String, Object> toMap(List<Element> elements,List<Map<String,Object>> list){
//
Element el = null;
String name = "";
//
Map<String, Object> map = new HashMap<String, Object>();
//
for(int i=0; i<elements.size();i++){
el = (Element) elements.get(i);
name = el.getName();
//如果是定义成数组
if(ARRAY_PROPERTY.contains(name)) {
//继续递归循环
List<Map<String,Object>> sublist = new ArrayList<Map<String,Object>>();
//
Map<String,Object> subMap = this.toMap(el.elements(),sublist);
//根据key获取是否已经存在
Object object = map.get(name);
//如果存在,合并
if(object !=null ){
List<Map<String,Object>> olist = (List<Map<String,Object>>)object;
olist.add(subMap);//
map.put(name, olist);
}else{//否则直接存入map
map.put(name, sublist);
}
}else {//单个值存入map
map.put(name,el.getTextTrim());
}
}
//存入list中
if(list!=null)
list.add(map);
//返回结果集合
return map;
}
/**
* 读取文本文件里的xml
* @return
* @throws Exception
*/
private static String readXML() throws Exception{
//
StringBuilder sb = new StringBuilder();
//
File file = new File("E:\\xml.txt");
//
if(file.exists() && file.isFile()){
InputStreamReader rd = new InputStreamReader(new FileInputStream(file), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(rd);
String str="";
while((str = bufferedReader.readLine()) != null){
sb.append(str);
}
rd.close();
}
//
return sb.toString();
}
/**
* main 方法
* @param args
*/
public static void main(String[] args) {
//实例化对象
ParseXML parseXML = new ParseXML();
//获取xml
String xml = new String();
try {
xml = parseXML.readXML();
//解析xml
Map<String, Object> result = parseXML.parserXml(xml);
//打印输出
System.out.println(result);
} catch (Exception e) {
//
System.err.print(e.getMessage());
}
}
}
解析结果:
{
CustList=[
{
FName=SMFromUserName,
MType=SMMsgType,
TName=SMToUserName,
MId=SMMsgId1234567890123456,
Content=SMContent,
Code=00,
SrcLabel=SMSrcLabel,
CTime=SMCreateTime1348831860
},
{
FName=2SMFromUserName,
MType=2SMMsgType,
TName=2SMToUserName,
SMCust=[
{
SM1=sm1val,
SM2=sm2val
},
{
SM1=sm3val,
SM2=sm4val
}
],
MId=2SMMsgId1234567890123456,
Content=2SMContent,
Code=200,
SrcLabel=2SMSrcLabel,
CTime=2SMCreateTime1348831860
}
],
Content=Success,
Code=1200
}