在开发过程中会调用soap接口,返回的数据就是xml形式,那么久需要对xml进行解析,对xml操作大家都还是比较不是很熟悉相比对于map的操作。所以我提供了这么一个方法,让大家对xml数据提取,转换成对map数据提取。
下面是import 的jar 包,一定要引用对,刚开始做的时候,好多Document包,比较困扰,索性我直接贴出来减少不必要的麻烦。
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* xml to map.
* void.
* think.
*
* @param rootElement
* @param map
*/
public static void findAndPutElement(Element rootElement, Map map) {
if (null == rootElement){
return;
}
@SuppressWarnings("unchecked")
List elementList = rootElement.elements();
for (Element e : elementList) {
if (null != map.get(e.getName())){
}
Object tempObj = null;
if (e.elements().size() < 1){
tempObj = e.getStringValue();
} else {
Map innerMap = new HashMap();
findAndPutElement(e, innerMap);
tempObj = innerMap;
}
if (null == map.get(e.getName())){
map.put(e.getName(), tempObj);
} else if (map.get(e.getName()) instanceof List){
@SuppressWarnings("unchecked")
List obj = (List) map.get(e.getName());
obj.add(tempObj);
} else{
List objList = new LinkedList();
objList.add(map.get(e.getName()));
objList.add(tempObj);
map.put(e.getName(), objList);
}
}
}
正如上面代码所示,将简单的xml 进行格式化,封装到map结构中,输入根节点,然后输入结果map就可以了。下面是待处理xml:
参考测试代码:
public static void main(String [] argv){
String xmlStr1 = "success1134rfsadf2223666666";
try {
Document document = DocumentHelper.parseText(xmlStr1);
Element root = document.getRootElement();
Map resultMap = new HashMap();
findAndPutElement(root, resultMap);
System.out.print(resultMap);
} catch (Exception e) {
e.printStackTrace();
}
}
下面是生成Map结构参考结果:
{
Status={
resultMsg=1,
result=success,
resCode=1
},
records={
record={
userInfo={
numInfos={
numInfo=[
{
indentNbrType=23,
indentNbr=22
},
{
indentNbrType=6666,
indentNbr=66
}
]
},
id=3,
name=4,
Remarks=rfsadf
}
}
}
}
后续会更新 字段包含属性的情况。如下:
期待后续更新~