XML|xml 解析成map

父类:

package com.siku.manorage.common.readsend.xml;
import java.io.StringReader;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class BaseReaderXml {
public SAXReader getSAXReader() {
return new SAXReader();
}
public Document getDocument(String file) throws Exception {
StringReader in = new StringReader(file);
return this.getSAXReader().read(in);
}
public Element getRootElement(String file) throws Exception {
return this.getDocument(file).getRootElement();
}


}
子类:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Element;
【XML|xml 解析成map】/**
* 接受前台传来数据(XML)到后台进行解析
*
**
*/
public class ReceiveClientXml extends BaseReaderXml {
/**
* 把拦截器里面的string 类型的xml 转化为一个map
* @param file
* @return 把前台传过来的xml 解析出来 放到一个map 里面
* @throws Exception
*/
@SuppressWarnings("unchecked")
public Map receivedClientXml(String file) throws Exception {
Map map = new HashMap();
List elementList = new ArrayList();
Element root = this.getRootElement(file);
Iterator it = root.elementIterator();
for (; it.hasNext(); )
{
Element ele = it.next();
if("element".equals(ele.getName().trim()))//二级结构..modified by zhangzhao 2010-3-27
{
Iterator it2 = ele.elementIterator();
HashMap map2 = new HashMap();
for(; it2.hasNext(); )
{
Element ele2 = it2.next();
map2.put(ele2.getName().trim(), ele2.getTextTrim());
}
elementList.add(map2);
}
else
{
map.put(ele.getName(), ele.getTextTrim());
}

}
map.put("elementList", elementList);
return map;
}
}


    推荐阅读