Dom4J解析xml⽂件动态转换为ListBean或者Map集合
⼤家在解析⼤量相似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</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</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.jeecmsmon.util;
import flect.Field;
import java.URL;
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 (GenericType().toString().equals("class java.lang.Integer")) {
field.set(obj, Integer.parseInt(value));
} else if (GenericType().toString().equals("boolean")) {
field.set(obj, Boolean.parseBoolean(value));
} else if (GenericType().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 = RootElement();
String root = et.getName();
// 查看返回码是否为真.
List<Element> list = doc.selectNodes("//" + root + "/resultCode");
if (!list.isEmpty() && list.size() > 0) {
Element element = (0);
String returnResult = Text();
if (returnResult.equals("0")) {
List<Element> father = doc.selectNodes("//" + root + "/"+ SimpleName()+"s"); //判断对象⽗节点是否有包含数据
if(father!=null&&!father.isEmpty()&&father.size()==1){
List<Element> userLists = (0).elements();
if (userLists!=null&&!list.isEmpty()) {
lists = new ArrayList<Object>();
for (Element e : userLists) {
List<Element> li = e.elements();
Class<?> cl = (Class<?>) Class.Name());
Object ob = cl.newInstance();
for (Element element2 : li) {
String name = Name();
String value = Text();
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 = ad(url);
Element et = RootElement();
String root = et.getName();
// 查看返回码是否为真.
List<Element> list = doc.selectNodes("//" + root + "/resultCode");
if (!list.isEmpty() && list.size() > 0) {
Element element = (0);
String returnResult = Text();
if (returnResult.equals("0")) {
List<Element> father = doc.selectNodes("//" + root + "/"+ SimpleName()+"s");
//判断对象⽗节点是否有包含数据
if(father!=null&&!father.isEmpty()&&father.size()==1){
List<Element> userLists = (0).elements();
if (userLists!=null&&!list.isEmpty()) {
lists = new ArrayList<Object>();
for (Element e : userLists) {
List<Element> li = e.elements();
Class<?> cl = (Class<?>) Class.Name());
Object ob = cl.newInstance();
for (Element element2 : li) {
String name = Name();
String value = Text();
Field field = ob.getClass().getDeclaredField(name);
field.setAccessible(true);
convertValue(field, ob, 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使用dom4j解析xml文件
* @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 = ad(new File(requestPath));
Document doc = ad(new URL(requestPath));
Element et = RootElement();
// 标记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.Name()); Object ob = cl.newInstance();
for (Element element2 : li) {
String name = Name();
String value = Text();
Field field = ob.getClass().getDeclaredField(name);
field.setAccessible(true);
convertValue(field, ob, value);
}
lists.add(ob);
}
} else {
maps.Name(), Text());
}
maps.SimpleName() + "_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 = RootElement();
String root = et.getName();
// 查看返回码是否为真.
List<Element> list = doc.selectNodes("//" + root + "/resultCode"); if (!list.isEmpty() && list.size() > 0) {
Element element = (0);
String returnResult = Text();
if (returnResult.equals("0")) {
bool = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return bool;
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论