最近通过xfire开发接口服务, 总是需要处理xml,在思索将xml映射到实体类中好还是映射到map中好,最后考虑到错误数据问题还是将xml映射到map中,代码贴出来 以供参考。
实体类
package com.yxw.xml.practice1.domain;
import java.util.Arrays;
import java.util.Date;
/**
* @author yxw
* @create 2018-08-16 10:28
* @desc
**/
public class Rkjbxx {
private String id;
private String name;
private String sex;
private int age;
private Date birthday;
private String no;
private String sid;
private String exp;
private String result;
private short ashort;
private long along;
private float afloat;
private double adouble;
private char achar;
private boolean bool;
private byte abyte;
private byte[] bytes;
public byte[] getBytes() {
return bytes;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getExp() {
return exp;
}
public void setExp(String exp) {
this.exp = exp;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public short getAshort() {
return ashort;
}
public void setAshort(short ashort) {
this.ashort = ashort;
}
public long getAlong() {
return along;
}
public void setAlong(long along) {
this.along = along;
}
public float getAfloat() {
return afloat;
}
public void setAfloat(float afloat) {
this.afloat = afloat;
}
public double getAdouble() {
return adouble;
}
public void setAdouble(double adouble) {
this.adouble = adouble;
}
public char getAchar() {
return achar;
}
public void setAchar(char achar) {
this.achar = achar;
}
public boolean isBool() {
return bool;
}
public void setBool(boolean bool) {
this.bool = bool;
}
public byte getAbyte() {
return abyte;
}
public void setAbyte(byte abyte) {
this.abyte = abyte;
}
@Override
public String toString() {
return "Rkjbxx{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", birthday=" + birthday +
", no='" + no + '\'' +
", sid='" + sid + '\'' +
", exp='" + exp + '\'' +
", result='" + result + '\'' +
", ashort=" + ashort +
", along=" + along +
", afloat=" + afloat +
", adouble=" + adouble +
", achar=" + achar +
", bool=" + bool +
", abyte=" + abyte +
", bytes=" + Arrays.toString(bytes) +
'}';
}
}
工具类
package com.yxw.xml.util;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author yxw
* @create 2018-08-16 10:31
* @desc
**/
public class XmlUtils {
/**
* xml转换为实体类list
* @param xml 要转换的xml xml格式 <CONDITIONS><CONDITION no="" sid = "" exp = "" result = "">...</CONDITION></CONDITIONS>
* @param clazz 实体类
* @return
*/
public static List resolveXmlToObjectList(String xml, Class clazz) throws DocumentException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
List resultList = new ArrayList();
Document document = DocumentHelper.parseText(xml);
Element rootElement = document.getRootElement();
List<Element> condition = rootElement.elements("CONDITION");
if(condition!=null&&condition.size()>0){
for(Element e : condition){
Object o = clazz.newInstance();
List<Attribute> attributes = e.attributes();
if(attributes!=null&&attributes.size()>0){
o = getObjectByReflect(o, attributes);
}
List<Element> elements = e.elements();
if(elements!=null && elements.size()>0){
o = getObjectByReflect(o, elements);
}
resultList.add(o);
}
return resultList;
}else{
return null;
}
}
/**
* 通过反射 将list里面的内容 反射到实体类中 此方法不一定共用 因为需要提前知道调用的方法,此处只是针对我的业务
* @param obj
* @param lists
* @return
* @throws NoSuchFieldException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
public static Object getObjectByReflect(Object obj, List lists) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
Object value = new Object();
Class clazz = obj.getClass();
for(Object $obj : lists){
Class<?> $clazz = $obj.getClass();
Method getNameMethod = $clazz.getMethod("getName");
Method getTextMethod = $clazz.getMethod("getText");
String attributeName = (String) getNameMethod.invoke($obj);
String attributeValue = (String) getTextMethod.invoke($obj);
Field field = clazz.getDeclaredField(attributeName.toLowerCase());
field.setAccessible(true);
Class<?> type = field.getType();
String methodName = "set" + attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1).toLowerCase();
value = getParamByType(type, attributeValue);
Method method = clazz.getMethod(methodName, type);
if(method!=null){
method.invoke(obj, value);
}
}
return obj;
}
/**
* 根据路径获取xml
* @param xmlPath xml路径
* @return
* @throws DocumentException
*/
public static String getXml(String xmlPath) throws DocumentException {
URL resource = XmlUtils.class.getResource(xmlPath);
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(resource);
return document.asXML();
}
/**
* 根据传入参数类型 将字符串转为对应类型
* @param type 传入参数类型
* @param value 传入字符串
* @return
*/
public static Object getParamByType(Class type, String value){
value = value.replace(" ", "");
Object result = new Object();
if(type==String.class){
result = value;
}else if(type == int.class||type==Integer.class){
result = Integer.parseInt(value);
}else if(type == float.class||type == Float.class){
result = Float.parseFloat(value);
}else if(type == double.class||type == Double.class){
result = Double.parseDouble(value);
}else if(type == long.class||type == Long.class){
result = Long.parseLong(value);
}else if(type == short.class||type == Short.class){
result = Short.parseShort(value);
}else if(type == byte.class||type == Byte.class){
result = Byte.parseByte(value);
}else if(type == char.class){
result = value.trim().charAt(0);
}else if(type == boolean.class || type == Boolean.class){
result = Boolean.parseBoolean(value);
}else if(type == Date.class){
result = strToDate(value);
}else if(type == byte[].class || type == Byte[].class){
result = value.getBytes();
}
return result;
}
/**
* 将字符串转为日期
* @param value
* @return
*/
public static Date strToDate(String value){
if("".equals(value)||value == null){
return null;
}
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
try {
date = sdf.parse(value);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* xml转换为Map类list
* @param xml
* @return
* @throws DocumentException
*/
public static List resolveXmlToMapList(String xml) throws DocumentException {
List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
Document document = DocumentHelper.parseText(xml);
List<Element> condition = document.getRootElement().elements("CONDITION");
for(Element element : condition){
Map resultMap = new HashMap();
List<Attribute> attributes = element.attributes();
if(attributes!=null&&attributes.size()>0){
for(Attribute attribute : attributes){
resultMap.put(attribute.getName(), attribute.getText().replace(" ", ""));
}
}
List<Element> elements = element.elements();
if(elements!=null&&elements.size()>0){
for(Element $element : elements){
resultMap.put($element.getName(), $element.getText().replace(" ", ""));
}
}
resultList.add(resultMap);
}
return resultList;
}
}
xml文件
<?xml version="1.0" encoding="UTF-8"?>
<CONDITIONS>
<CONDITION no="1" sid="x" exp="y" result="z">
<id>1 2 3</id>
<name>xxx </name>
<sex>1 </sex>
<age>25</age>
<birthday>20180225</birthday>
<aShort>1 23</aShort>
<aLong>1 43</aLong>
<aFloat>1 .2</aFloat>
<aDouble>2.111</aDouble>
<aChar>1232</aChar>
<bool>f alse</bool>
<aByte>127</aByte>
<bytes>11</bytes>
</CONDITION>
<CONDITION no="1" sid="" exp="" result="">
<id>1 2 3</id>
<name>xx </name>
<sex>1 </sex>
<age>25</age>
<birthday>20180225</birthday>
<aShort>1 23</aShort>
<aLong>1 43</aLong>
<aFloat>1 .2</aFloat>
<aDouble>2.111</aDouble>
<aChar>1232</aChar>
<bool>f alse</bool>
<aByte>127</aByte>
<bytes>11</bytes>
</CONDITION>
</CONDITIONS>
映射到实体类的list 的main方法
package com.yxw.xml.practice1.test;
import com.yxw.xml.practice1.domain.Rkjbxx;
import com.yxw.xml.util.XmlUtils;
import org.dom4j.DocumentException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author yxw
* @create 2018-08-16 11:03
* @desc
**/
public class Demo1 {
public static void main(String[] args) {
//此处是xml文件的路径
String xmlPath = "/com/yxw/xml/practice1/file/1ton.xml";
String xml = "";
List<Rkjbxx> rkjbxxList = new ArrayList<Rkjbxx>();
Rkjbxx rkjbxx = new Rkjbxx();
try {
xml = XmlUtils.getXml(xmlPath);
}catch (DocumentException e) {
e.printStackTrace();
}
if(xml!=null && xml.length()>0){
try {
rkjbxxList = XmlUtils.resolveXmlToObjectList(xml, Rkjbxx.class);
} catch (DocumentException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
System.out.println(Arrays.toString(rkjbxxList.toArray()));
}
}
映射到map类的list的main方法
package com.yxw.xml.practice2.test;
import com.yxw.xml.util.XmlUtils;
import org.dom4j.DocumentException;
import java.util.List;
import java.util.Map;
/**
* @author yxw
* @create 2018-08-20 15:44
* @desc
**/
public class Demo1 {
public static void main(String[] args) {
String xmlPath = "/com/yxw/xml/practice2/file/1ton.xml";
String xml = "";
try {
xml = XmlUtils.getXml(xmlPath);
} catch (DocumentException e) {
e.printStackTrace();
}
if(xml!=null && xml.length()>0){
try {
List<Map<String, String>> list = XmlUtils.resolveXmlToMapList(xml);
for(Map<String, String> map : list){
for(String key : map.keySet()){
System.out.println(key + "------------" + map.get(key));
}
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
}
版权声明:本文为weixin_42442986原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。