xml字符串转map
2018-01-19 09:20
141 查看
public static Map<String, String> xmlStrToMap(String xml)
throws DocumentException {
Document document = DocumentHelper.parseText(xml);
Element root = document.getRootElement();
return parseElement(root);
}
/**
* 解析Element
*
* @param root
* @return
*/
@SuppressWarnings("unchecked")
private static Map<String, String> parseElement(Element root) {
Iterator<Element> rootItor = root.elementIterator();
Map<String, String> rsltMap = new HashMap<>();
while (rootItor.hasNext()) {
Element tmpElement = rootItor.next();
if (!tmpElement.isTextOnly()) {
Iterator<Element> headItor = tmpElement.elementIterator();
while (headItor.hasNext()) {
Element hElement = headItor.next();
if (hElement.isTextOnly()) {
rsltMap.put(hElement.getName(), hElement.getTextTrim());
} else {
rsltMap.putAll(parseElement(hElement));
}
}
}else{
rsltMap.put(tmpElement.getName(), tmpElement.getTextTrim());
}
}
return rsltMap;
}
throws DocumentException {
Document document = DocumentHelper.parseText(xml);
Element root = document.getRootElement();
return parseElement(root);
}
/**
* 解析Element
*
* @param root
* @return
*/
@SuppressWarnings("unchecked")
private static Map<String, String> parseElement(Element root) {
Iterator<Element> rootItor = root.elementIterator();
Map<String, String> rsltMap = new HashMap<>();
while (rootItor.hasNext()) {
Element tmpElement = rootItor.next();
if (!tmpElement.isTextOnly()) {
Iterator<Element> headItor = tmpElement.elementIterator();
while (headItor.hasNext()) {
Element hElement = headItor.next();
if (hElement.isTextOnly()) {
rsltMap.put(hElement.getName(), hElement.getTextTrim());
} else {
rsltMap.putAll(parseElement(hElement));
}
}
}else{
rsltMap.put(tmpElement.getName(), tmpElement.getTextTrim());
}
}
return rsltMap;
}
相关文章推荐
- java使用jdom架包解析xml字符串dom原理并保存map对象
- java实现对象转换为map、xml字符串转化为map、map转化为xml字符串
- xml String字符串解析 map转xml
- 解析格式为纯字符串的MAP封装起来的XML:(1)
- XML转Map类型 和 对象类型转XML字符串
- 解析格式为纯字符串的MAP封装起来的XML:(2)
- 将xml字符串转换成map,list 的转换
- Java Map转成xml标签字符串
- Xml字符串转Map
- xml字符串与map之间的相互转换
- 将Map和List<Map>zhuan转换成xml字符串
- XML字符串转Map
- XML字符串与MAP格式互转
- 解析字符串XML成map
- 字符串作为map的key
- DataSet、DataTable、DataView格式转换成XML字符串、XML文件
- Android 中从res/values/strings.xml中读取具体的字符串的方法
- ecshop优化修改sitemap.xml到根目录
- 使用JAXB实现JAVA对象和XML字符串的互相转换实例
- rails中如何将字符串转换成xml?