xml转list

前端之家收集整理的这篇文章主要介绍了xml转list前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
大家在解析大量相似xml文件的时候是否会遇到这样一个问题:冗余的代码去set定义的实体对象Bean的值,基本都是一样的操作

而且毫无任何代码价值可言所以在这写了一个简单的例子,类封装了几个方法你只需传入xml文件,或者URL路径。和Bean.Class 类名

即可自动传回你需要的List集合。

需要解析的xml文件

<?xml version="1.0" encoding="UTF-8"?>
<messages>
<resultCode>0</resultCode>
<totalCount>2</totalCount>
<UserLists>
<UserList>
<userId>0</userId>
<loginName>张三0</loginName>
<email>qsina0@sina.com</email>
<userType>1</userType>
<status>1</status>
<roleType>1</roleType>
<registerIP>192.168.1.0</registerIP>
<registerTime>2012-06-07 15:35:33</registerTime>
</UserList>
<UserList>
<userId>1</userId>
<loginName>张三1</loginName>
<email>qsina1@sina.com</email>
<userType>1</userType>
<status>1</status>
<roleType>1</roleType>
<registerIP>192.168.1.1</registerIP>
<registerTime>2012-06-07 15:35:33</registerTime>
</UserList>
</UserLists>
</messages>

在进行相关操作中需要如下包:

下面是贴出的代码

package com.jeecms.common.util;

import java.lang.reflect.Field;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlParseUtil {
/**
* 反射设置实体不同类型字段的值 <暂时只支持 日期 字符串 boolean Integer值设置 待扩建>
*
* @param field
* @param obj
* @param value
* @throws Exception
*/
public static void convertValue(Field field,Object obj,String value)
throws Exception {
SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (field.getGenericType().toString().equals("class java.lang.Integer")) {
field.set(obj,Integer.parseInt(value));
} else if (field.getGenericType().toString().equals("boolean")) {
field.set(obj,Boolean.parseBoolean(value));
} else if (field.getGenericType().toString().equals(
"class java.util.Date")) {
field.set(obj,sim.parse(value));
} else {
field.set(obj,value);
}

}

/**
* 解析xml文件返回保存cls的List集合,如果返回码resultCode=1时则返回List为null
*
* @param xml
* @param cls
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static List<?> parseXml2List(String xml,Class<?> cls)
throws Exception {
List<Object> lists = null;
Document doc = DocumentHelper.parseText(xml);
Element et = doc.getRootElement();
String root = et.getName();
// 查看返回码是否为真.
List<Element> list = doc.selectNodes("//" + root + "/resultCode");
if (!list.isEmpty() && list.size() > 0) {
Element element = list.get(0);
String returnResult = element.getText();
if (returnResult.equals("0")) {
List<Element> father = doc.selectNodes("//" + root + "/"+ cls.getSimpleName()+"s");
//判断对象父节点是否有包含数据
if(father!=null&&!father.isEmpty()&&father.size()==1){
List<Element> userLists = father.get(0).elements();
if (userLists!=null&&!list.isEmpty()) {
lists = new ArrayList<Object>();
for (Element e : userLists) {
List<Element> li = e.elements();
Class<?> cl = (Class<?>) Class.forName(cls.getName());
Object ob = cl.newInstance();
for (Element element2 : li) {
String name = element2.getName();
String value = element2.getText();
Field field = ob.getClass().getDeclaredField(name);
field.setAccessible(true);
convertValue(field,ob,value);
}
lists.add(ob);
}
}
}
}

}
return lists;
}

/**
* 解析xml文件返回保存cls的List集合,如果返回码resultCode=1时则返回List为null
*
* @param url
* @param cls
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static List<?> parseXml2List(URL url,Class<?> cls)
throws Exception {
List<Object> lists = null;
SAXReader saxReader = new SAXReader();
Document doc = saxReader.read(url);
Element et = doc.getRootElement();
String root = et.getName();
// 查看返回码是否为真.
List<Element> list = doc.selectNodes("//" + root + "/resultCode");
if (!list.isEmpty() && list.size() > 0) {
Element element = list.get(0);
String returnResult = element.getText();
if (returnResult.equals("0")) {
List<Element> father = doc.selectNodes("//" + root + "/"+ cls.getSimpleName()+"s");
//判断对象父节点是否有包含数据
if(father!=null&&!father.isEmpty()&&father.size()==1){
List<Element> userLists = father.get(0).elements();
if (userLists!=null&&!list.isEmpty()) {
lists = new ArrayList<Object>();
for (Element e : userLists) {
List<Element> li = e.elements();
Class<?> cl = (Class<?>) Class.forName(cls.getName());
Object ob = cl.newInstance();
for (Element element2 : li) {
String name = element2.getName();
String value = element2.getText();
Field field = ob.getClass().getDeclaredField(name);
field.setAccessible(true);
convertValue(field,value);
}
lists.add(ob);
}
}
}
}

}
return lists;
}
/**
* 解析xml文件返回保存Map的集合,map中可能包含key值为returnCode、desc、totalCount等单字段.
* 也可能包含存储对象为List<cls>的集合值.
* 获取List值key cls_List
* @param requestPath
* @param cls
* @return map
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static Map<String,Object> parseXml2Map(String requestPath,
Class<?> cls) throws Exception {
Map<String,Object> maps = new HashMap<String,Object>();
List<Object> lists = new ArrayList<Object>();
SAXReader saxReader = new SAXReader();
//Document doc = saxReader.read(new File(requestPath));
Document doc = saxReader.read(new URL(requestPath));
Element et = doc.getRootElement();
// 标记List是否为空
// boolean bool = true ;
// 根节点名字
List<Element> rList = et.elements();
for (Element element : rList) {
List<Element> rLists = element.elements();
if (!rLists.isEmpty() && rLists.size() > 0) {
//bool = false;
// 判断二级节点
for (Element e : rLists) {
List<Element> li = e.elements();
Class<?> cl = (Class<?>) Class.forName(cls.getName());
Object ob = cl.newInstance();
for (Element element2 : li) {
String name = element2.getName();
String value = element2.getText();
Field field = ob.getClass().getDeclaredField(name);
field.setAccessible(true);
convertValue(field,value);
}
lists.add(ob);
}
} else {
maps.put(element.getName(),element.getText());
}
maps.put(cls.getSimpleName() + "_List",lists);
}
return maps;
}

/**
* 只获取返回码0为保存成功(true)1为保存失败(false)
*/
@SuppressWarnings("unchecked")
public static boolean parseXmlReturnCode(String xml) {
boolean bool = false;
try {
Document doc = DocumentHelper.parseText(xml);
Element et = doc.getRootElement();
String root = et.getName();
// 查看返回码是否为真.
List<Element> list = doc.selectNodes("//" + root + "/resultCode");
if (!list.isEmpty() && list.size() > 0) {
Element element = list.get(0);
String returnResult = element.getText();
if (returnResult.equals("0")) {
bool = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return bool;
}
}
////////////////////
很多朋友遇到xml,map和json互转的问题,在开发中xml和json越来越重要了。我就把我的工具类贴上来。


  1. package com.shine.framework.core.util;
  2. import java.io.ByteArrayOutputStream;
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.Iterator;
  6. import java.util.List;
  7. import java.util.Map;
  8. import net.sf.json.JSON;
  9. import net.sf.json.JSONSerializer;
  10. import net.sf.json.xml.XMLSerializer;
  11. import org.dom4j.Document;
  12. import org.dom4j.DocumentHelper;
  13. import org.dom4j.Element;
  14. import org.dom4j.io.OutputFormat;
  15. import org.dom4j.io.XMLWriter;
  16. /**
  17. * common xml conver utility
  18. *
  19. * @author viruscodecn@gmail.com
  20. * @version Framework 2010.10.26
  21. * @url http://blog.csdn.net/arjick/article/details/6251777
  22. */
  23. public class XmlConverUtil {
  24. /**
  25. * map to xml xml <node><key label="key1">value1</key><key
  26. * label="key2">value2</key>......</node>
  27. *
  28. * @param map
  29. * @return
  30. */
  31. public static String maptoXml(Map map) {
  32. Document document = DocumentHelper.createDocument();
  33. Element nodeElement = document.addElement("node");
  34. for (Object obj : map.keySet()) {
  35. Element keyElement = nodeElement.addElement("key");
  36. keyElement.addAttribute("label",String.valueOf(obj));
  37. keyElement.setText(String.valueOf(map.get(obj)));
  38. }
  39. return doc2String(document);
  40. }
  41. /**
  42. * list to xml xml <nodes><node><key label="key1">value1</key><key
  43. * label="key2">value2</key>......</node><node><key
  44. * label="key1">value1</key><key
  45. * label="key2">value2</key>......</node></nodes>
  46. *
  47. * @param list
  48. * @return
  49. */
  50. public static String listtoXml(List list) throws Exception {
  51. Document document = DocumentHelper.createDocument();
  52. Element nodesElement = document.addElement("nodes");
  53. int i = 0;
  54. for (Object o : list) {
  55. Element nodeElement = nodesElement.addElement("node");
  56. if (o instanceof Map) {
  57. for (Object obj : ((Map) o).keySet()) {
  58. Element keyElement = nodeElement.addElement("key");
  59. keyElement.addAttribute("label",String.valueOf(obj));
  60. keyElement.setText(String.valueOf(((Map) o).get(obj)));
  61. }
  62. } else {
  63. Element keyElement = nodeElement.addElement("key");
  64. keyElement.addAttribute("label",String.valueOf(i));
  65. keyElement.setText(String.valueOf(o));
  66. }
  67. i++;
  68. }
  69. return doc2String(document);
  70. }
  71. /**
  72. * json to xml {"node":{"key":{"@label":"key1","#text":"value1"}}} conver
  73. * <o><node class="object"><key class="object"
  74. * label="key1">value1</key></node></o>
  75. *
  76. * @param json
  77. * @return
  78. */
  79. public static String jsontoXml(String json) {
  80. try {
  81. XMLSerializer serializer = new XMLSerializer();
  82. JSON jsonObject = JSONSerializer.toJSON(json);
  83. return serializer.write(jsonObject);
  84. } catch (Exception e) {
  85. e.printStackTrace();
  86. }
  87. return null;
  88. }
  89. /**
  90. * xml to map xml <node><key label="key1">value1</key><key
  91. * label="key2">value2</key>......</node>
  92. *
  93. * @param xml
  94. * @return
  95. */
  96. public static Map xmltoMap(String xml) {
  97. try {
  98. Map map = new HashMap();
  99. Document document = DocumentHelper.parseText(xml);
  100. Element nodeElement = document.getRootElement();
  101. List node = nodeElement.elements();
  102. for (Iterator it = node.iterator(); it.hasNext();) {
  103. Element elm = (Element) it.next();
  104. map.put(elm.attributeValue("label"),elm.getText());
  105. elm = null;
  106. }
  107. node = null;
  108. nodeElement = null;
  109. document = null;
  110. return map;
  111. } catch (Exception e) {
  112. e.printStackTrace();
  113. }
  114. return null;
  115. }
  116. /**
  117. * xml to list xml <nodes><node><key label="key1">value1</key><key
  118. * label="key2">value2</key>......</node><node><key
  119. * label="key1">value1</key><key
  120. * label="key2">value2</key>......</node></nodes>
  121. *
  122. * @param xml
  123. * @return
  124. */
  125. public static List xmltoList(String xml) {
  126. try {
  127. List<Map> list = new ArrayList<Map>();
  128. Document document = DocumentHelper.parseText(xml);
  129. Element nodesElement = document.getRootElement();
  130. List nodes = nodesElement.elements();
  131. for (Iterator its = nodes.iterator(); its.hasNext();) {
  132. Element nodeElement = (Element) its.next();
  133. Map map = xmltoMap(nodeElement.asXML());
  134. list.add(map);
  135. map = null;
  136. }
  137. nodes = null;
  138. nodesElement = null;
  139. document = null;
  140. return list;
  141. } catch (Exception e) {
  142. e.printStackTrace();
  143. }
  144. return null;
  145. }
  146. /**
  147. * xml to json <node><key label="key1">value1</key></node> 转化为
  148. * {"key":{"@label":"key1","#text":"value1"}}
  149. *
  150. * @param xml
  151. * @return
  152. */
  153. public static String xmltoJson(String xml) {
  154. XMLSerializer xmlSerializer = new XMLSerializer();
  155. return xmlSerializer.read(xml).toString();
  156. }
  157. /**
  158. *
  159. * @param document
  160. * @return
  161. */
  162. public static String doc2String(Document document) {
  163. String s = "";
  164. try {
  165. // 使用输出流来进行转化
  166. ByteArrayOutputStream out = new ByteArrayOutputStream();
  167. // 使用UTF-8编码
  168. OutputFormat format = new OutputFormat(" ",true,"UTF-8");
  169. XMLWriter writer = new XMLWriter(out,format);
  170. writer.write(document);
  171. s = out.toString("UTF-8");
  172. } catch (Exception ex) {
  173. ex.printStackTrace();
  174. }
  175. return s;
  176. }
  177. }
//////////////

将xml转换成Map,能够应对不用结构的xml,而不是只针对固定格式的xml.
转换规则:
1.主要是Map与List的互相嵌套
2.同名称的节点会被装进List

示例:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.Element;
public class XmlUtils {
@SuppressWarnings("unchecked")
public static Map<String,Object> Dom2Map(Document doc){
Map<String,Object> map = new HashMap<String,Object>();
if(doc == null)
return map;
Element root = doc.getRootElement();
for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
Element e = (Element) iterator.next();
List list = e.elements();
if(list.size() > 0){
map.put(e.getName(),Dom2Map(e));
}else
map.put(e.getName(),e.getText());
}
return map;
}
@SuppressWarnings("unchecked")
public static Map Dom2Map(Element e){
Map map = new HashMap();
List list = e.elements();
if(list.size() > 0){
for (int i = 0;i < list.size(); i++) {
Element iter = (Element) list.get(i);
List mapList = new ArrayList();

if(iter.elements().size() > 0){
Map m = Dom2Map(iter);
if(map.get(iter.getName()) != null){
Object obj = map.get(iter.getName());
if(!obj.getClass().getName().equals("java.util.ArrayList")){
mapList = new ArrayList();
mapList.add(obj);
mapList.add(m);
}
if(obj.getClass().getName().equals("java.util.ArrayList")){
mapList = (List) obj;
mapList.add(m);
}
map.put(iter.getName(),mapList);
}else
map.put(iter.getName(),m);
}
else{
if(map.get(iter.getName()) != null){
Object obj = map.get(iter.getName());
if(!obj.getClass().getName().equals("java.util.ArrayList")){
mapList = new ArrayList();
mapList.add(obj);
mapList.add(iter.getText());
}
if(obj.getClass().getName().equals("java.util.ArrayList")){
mapList = (List) obj;
mapList.add(iter.getText());
}
map.put(iter.getName(),iter.getText());
}
}
}else
map.put(e.getName(),e.getText());
return map;
}
}
测试类:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

public class XmlToMapDemo {
public static void main(String[] args) throws IOException,
DocumentException {

FileInputStream fis = new FileInputStream("d://a.xml");
byte[] b = new byte[fis.available()];
fis.read(b);
String str = new String(b);

Document doc = DocumentHelper.parseText(str);

System.out.println(doc.asXML());

long beginTime = System.currentTimeMillis();

Map<String,Object> map = XmlUtils.Dom2Map(doc);

System.out.println(map.toString());

System.out.println("Use time:"+(System.currentTimeMillis()-beginTime));

} }

原文链接:https://www.f2er.com/xml/298290.html

猜你在找的XML相关文章