Java复杂XML转Object对象实例(⼀)
Java 复杂 XML转Object 对象实例:
在实际⼯作当中与第三⽅接⼝交互报⽂很多情况下都是XML格式,会⽤⼀些开源的解析XML映射Object对象⼯具类.很多时候⽹上的开源框架⼯具类可能存在⼀些不兼容现有系统.因此通过dom4j单个解析xml⼯作繁琐、代码冗余。
下⾯给⼤家介绍下⾃⼰研发复杂XML转Object对象,通过Java基础反射机制、dom4j、开发完成.,在⼯作中已经⼤范围使⽤。⾮常简单使⽤,⽆需⼤量引⽤第三⽅jar。有测试类⽰例,有⼯具类。使⽤说明:
引⽤开源jar包dom4j
直接看如下⽰例:
package testxml;
import xml.XMLObjectUtils;
public class Text02 {
public static void main(String[] args) {
String str = " ".trim();
if(!"".equals(str)) {
System.out.println("字符串不为空");
}
test01();
}
private static void test01() {
// 调⽤核⼼XML转Object ⽅法
PackageXml pack = (PackageXml) lToObj(PackageXml.class, getStrXml());
System.out.println("Head- requestId :" + Head().getRequestId());
System.out.println("Head- requestTime :" + Head().getRequestTime());
for(Person per : Body().getPersons().getPerson()) {
System.out.println("person - name:" + NameXml());
}
for(Person per : Persons().getPerson()) {
System.out.println("person - name:" + NameXml());
}
}
public static String getStrXml() {
String strXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<PackageXml>"
+ " <head>"
+ " <requestId>201809181010591537236659245908</requestId>"
+ " <requestTime>2018-12-12 12:12:12</requestTime>"
+ " </head>"
+ " <body>"
+ " <persons>"
+ " <person>"
+ " <nameXml>蒋⼲</nameXml>"
+ " </person>"
+ " <person>"
+ " <nameXml>蒋⼲</nameXml>"
+ " </person>"
+ " </person>"
+ " </persons>"
+ " </body>"
+ " <persons>"
+ " <person>"
+ " <nameXml>蒋⼲</nameXml>"
+ " </person>"
+ " <person>"
+ " <nameXml>蒋⼲</nameXml>"
+ " </person>"
+ " </persons>"
+ "</PackageXml>";
return strXml;
}
public String strFilter(String str){
String strFile = null;
if(str != null && !"".equals(str)){
strFile = str.substring(0, str.indexOf("<?"));
str = place(strFile, "");
object to}
return str;
}
}
⼯具类:XMLObjectUtils.java
package xml;
import java.io.UnsupportedEncodingException;
import flect.Field;
import flect.InvocationTargetException;
import flect.Method;
import flect.ParameterizedType;
import flect.Type;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* XML转Object V1.0 ⽀持List、Set、Object类型<br>
* XML定义节点名称与Object属性名称要保持⼀致,不区分⼤⼩写。 * <br>
* @User: AndyLee
* @Time:2018年9⽉18⽇下午8:48:49
*
*/
public class XMLObjectUtils {
/**
* ⽅法名称: xmlMappedObj<br>
* 描述:xml ⾃动映射成对对象Object :
* 描述:xml ⾃动映射成对对象Object :
* 属性⽀持:
* 基本类型、String、Set、List、Object 等
* 作者: AndyLee
* 修改⽇期:2018年9⽉18⽇下午8:48:49
* @param className 类名全路径
* @param xmlStr
* @return
*/
@SuppressWarnings("rawtypes")
public static <T> Object xmlToObj(String className ,String strXml){ Object obj = null;
try {
obj = getObject(className);
Class clzz = getInstance(className);
Element element = getElement(strXml);
xmlToObj(className, element, obj, clzz);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return obj ;
}
/**
* ⽅法名称: xmlMappedObj<br>
* 描述:xml ⾃动映射成对对象Object :
* 属性⽀持:
* 基本类型、String、Set、List、Object 等
* 作者: AndyLee
* 修改⽇期:2018年9⽉18⽇下午8:48:49
* @param clz 类名.class
* @param strXml
* @return
*/
@SuppressWarnings("rawtypes")
public static <T> Object xmlToObj(Class clz ,String strXml){
Object obj = null ;
try {
String className = Name();
obj = getObject(className);
Class clzz = getInstance(className);
Element element = getElement(strXml);
xmlToObj(className, element, obj, clzz);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return obj ;
}
public static <T> Object toXML1(String className ,String respXML){ Object obj = getObject(className);
Class clzz = getInstance(className);
Element element = getElement(respXML);
for (Field field : getInstance(className).getDeclaredFields()) {
Iterator iterator = element.elementIterator();
while(iterator.hasNext()){
Element el = (Element) ();
Name().Name())){
field = getField(clzz, el.getName());
field.setAccessible(true);
try {
field.set(obj, el.getText());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return obj ;
}
public static Element getElement(String xml){
Element element = null ;
Document doc = null ;
try {
doc = DocumentHelper.parseText(xml);
element = RootElement() ;
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return element ;
}
/*public static String objToJosn(Object obj){
if(obj != null){
return JSONObject.fromObject(obj).toString();
}
return "" ;
}*/
/**
* Object - 》 XML 属性只⽀持String类转换 <br>
* @param obj 对象
* @return <br>
*/
@SuppressWarnings("rawtypes")
public static String froXML(Object obj){
SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>(); Class clzz = Class();
for (Field f : DeclaredFields()){
GenericType().toString().equals("class java.lang.String")){
Method m = getMethod(clzz, "get" + Name()));
String value = getValue(m, obj);
if(value != null){
packageParams.Name(), value);
}
}
}
return objToXML(packageParams) ;
}
@SuppressWarnings("rawtypes")
public static String getSign(Object obj){
SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>(); Class clzz = Class();
for (Field f : DeclaredFields()){
GenericType().toString().equals("class java.lang.String")){
Method m = getMethod(clzz, "get" + Name()));
String value = getValue(m, obj);
if(value != null){
packageParams.Name(), value);
}
}
}
return objToXML(packageParams) ;
}
private static String getValue(Method method ,Object obj){ String value = null ;
try {
value = (String) method.invoke(obj);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value ;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Method getMethod(Class clzz ,String name){ Method method = null ;
try {
method = Method(name);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return method ;
}
private static String getMethodName(String fildeName){ byte[] items = Bytes();
items[0] = (byte) ((char) items[0] - 'a' + 'A');
return new String(items);
}
@SuppressWarnings("rawtypes")
private static Field getField(Class clzz ,String labelName){ Field field = null ;
try {
field = DeclaredField(labelName);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return field ;
}
/*private static JSONObject getJson(String json){
JSONObject jsonObject = null ;
try {
jsonObject = JSONObject.fromObject(json) ;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论