自定义的一个对象转xml的工具

本文介绍了一款自定义的Java工具类,用于将各种Java对象(包括List、Map、基本类型及其数组)转换成XML格式。该工具利用反射机制遍历对象的属性,并根据XML注解(如@XmlRootElement、@XmlElement、@XmlAttribute等)生成相应的XML标签。

 

配合下面这几个注解使用

javax.xml.bind.annotation.XmlAttribute;

javax.xml.bind.annotation.XmlElement;
javax.xml.bind.annotation.XmlElementWrapper;
javax.xml.bind.annotation.XmlRootElement;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import com.csair.cod.common.JaxbAdapterScTime;

/**
 *     自定义的对象转XML工具;
 *    现在 还不支持  object[];
 *
 *     @author liuyuhong;
 *     @date 2018-08-09;
 *     
 *
 */
public class XMLutil {
    
    /**
     * 
     * @param obj
     * @return
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     * @throws SecurityException
     */
    public static <T> String Toxml(Object obj,Type type) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{   
        String XML = "";
        if(obj instanceof List){
            String rootNameAnnotationStr = "";
            if(type != null){
                ParameterizedType ptClass =(ParameterizedType) type;
                Class clasz = (Class) ptClass.getActualTypeArguments()[0];
                XmlRootElement annotation = (XmlRootElement) clasz.getAnnotation(XmlRootElement.class);
                
                if(annotation != null){
                    rootNameAnnotationStr = annotation.name();
                }
            }
            List list = (List)obj;
            XML = listToxml(list,rootNameAnnotationStr,rootNameAnnotationStr + "s");
        }else if(obj instanceof Map){
            Map map = (Map) obj;
            XML = mapToxml(map, null);
        }else if(obj instanceof Byte | obj instanceof Short | 
                obj instanceof Integer | obj instanceof Long | obj instanceof Float |
                obj instanceof Double | obj instanceof Character |
                obj instanceof Boolean | obj instanceof String
                ){
            StringBuffer sb = new StringBuffer();
            sb.append("<"+ obj.getClass().getSimpleName() +">");
            sb.append(obj.toString());
            sb.append("</"+ obj.getClass().getSimpleName() +">");
            XML = sb.toString();
            
        }else{
            XML = objToxml(obj,null);
        }
        return XML;
    } 

    public static <T> String objToxml(T obj,String rootName) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
         StringBuffer sb = new StringBuffer();
        //获取根标签;
        if(rootName == null || rootName.equals("")){
            Class<? extends Object> clasz = obj.getClass();
            XmlRootElement annotation = clasz.getAnnotation(XmlRootElement.class);
            if(annotation == null || annotation.equals("")){
                rootName = clasz.getSimpleName();
            }else{
                rootName = annotation.name();
            }
        }
        if(obj == null || obj.equals("")){
            sb.append("</"+ rootName +">");
            return sb.toString();
         }
        Field[] properties = obj.getClass().getDeclaredFields();
        List<Field> allFields = Arrays.asList(properties);
        allFields = new ArrayList<Field>(allFields);
        List<Field> attributefields = new ArrayList<Field>();
        for(Field field:allFields){
            XmlAttribute annotation = field.getAnnotation(XmlAttribute.class);
            if(annotation != null){
                attributefields.add(field);
            }
        }
        allFields.removeAll(attributefields);
        sb.append("<"+ rootName);
        for(Field field:attributefields){
            if(Modifier.isStatic(field.getModifiers())){
                continue;
            }
            Method meth = obj.getClass().getMethod("get"+ field.getName().substring(0, 1).toUpperCase()+ field.getName().substring(1));   
            Object invoke = meth.invoke(obj);
            sb.append(" " + field.getName()+"="+"\""+invoke.toString()+"\"");
        }
        sb.append(">");
        //设置子标签;
        for (Field field:allFields) {                      
            //反射get方法       
            if(Modifier.isStatic(field.getModifiers())){
                continue;
            }
            Method meth = obj.getClass().getMethod("get"+ field.getName().substring(0, 1).toUpperCase()+ field.getName().substring(1));   
            //为二级节点添加属性,属性值为对应属性的值   
            Object object = meth.invoke(obj);
            if(object == null){
                continue;
            }
            if(object.equals("")){
                sb.append("<"+ field.getName() +">");
                sb.append("");
                sb.append("</"+ field.getName() +">");
                continue;
            }
            if(object instanceof List){
                XmlElementWrapper elementWrapperAnnotation = field.getAnnotation(XmlElementWrapper.class);
                XmlElement elementAnnotation = field.getAnnotation(XmlElement.class);
                String rootAnnotationStr = "";
                String rootNameAnnotationStr = "";
                if(elementWrapperAnnotation != null){
                    rootAnnotationStr = elementWrapperAnnotation.name();
                }
                if(elementAnnotation != null){
                    rootNameAnnotationStr = elementAnnotation.name();
                }
                List list = (List)object;
                String str = listToxml(list,rootNameAnnotationStr,rootAnnotationStr);
                sb.append(str);
                continue;
            }
            if(object instanceof Map){
                Map map = (Map) object;
                String str = mapToxml(map,null);
                sb.append(str);
                continue;
            }
            if(object.getClass().isArray()){
                String arrayStr = "";
                if(object instanceof byte[]){
                    System.out.println("1");
                    byte[] b =(byte[]) object;
                    arrayStr = Base64.getEncoder().encodeToString(b);
                    //System.out.println(arrayStr);
                    //arrayStr = new String(b);
                }else if(object instanceof int[]){
                    System.out.println("2");
                    int[] iArrary =  (int[]) object;
                    for(int ii:iArrary){
                        arrayStr += Integer.toString(ii);
                    }
                }else{
                    Object[] arr = (Object[]) object;
                }
                sb.append("<"+ field.getName() +">");
                sb.append(new String(arrayStr));
                sb.append("</"+ field.getName() +">");
                continue;
            }
            if(object instanceof Date){
                XmlJavaTypeAdapter javaTypeAdapterAnnotation = field.getAnnotation(XmlJavaTypeAdapter.class);
                String cont = "";
                Class<? extends XmlAdapter> javaType = null;
                if(javaTypeAdapterAnnotation == null){
                    javaType = JaxbAdapterScTime.class;
                }
                javaType = javaTypeAdapterAnnotation.value();
                Method method = javaType.getMethod("marshal", Date.class);
                try {
                    cont = (String) method.invoke(javaType.newInstance(), object);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                }
                sb.append("<"+ field.getName() +">");
                sb.append(cont);
                sb.append("</"+ field.getName() +">");
                continue;
                
            }
            if(!(object instanceof Byte | object instanceof Short | 
                    object instanceof Integer | object instanceof Long | object instanceof Float |
                    object instanceof Double | object instanceof Character |
                    object instanceof Boolean | object instanceof String)) {
                XmlElement elementannotation = field.getAnnotation(XmlElement.class);
                String rootNameAnnotationStr = "";
                if(elementannotation != null){
                    rootNameAnnotationStr = elementannotation.name();
                }
                sb.append(objToxml(object,rootNameAnnotationStr));
                continue;
            }
            sb.append("<"+ field.getName() +">");
            sb.append(object.toString());
            sb.append("</"+ field.getName() +">");
        }
        sb.append("</"+ rootName +">");
        String match = "<"+ rootName +"></"+ rootName +">";
        boolean matches = sb.toString().matches(match);
        if(matches){
            return "<"+ rootName +"/>";
        }
        return sb.toString();
    }
    
    public static <T> String listToxml(List<T> entityPropertys,String rootName, String root) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        StringBuffer sb = new StringBuffer();
        //获取根标签;
        if(entityPropertys.size() <= 0){
            if(!(root.equals("") || root == null)){
                if(rootName.equals("") || rootName == null){
                    return sb.append("<"+ root +"/>").toString();
                }
                return sb.append("<"+ rootName+"s></"+ rootName +"s>").toString();
            }
            return "";
        }
        if(rootName == null || rootName.equals("")){
            T obj = entityPropertys.get(0);
            Class<? extends Object> clasz = obj.getClass();
            XmlRootElement annotation = (XmlRootElement) clasz.getAnnotation(XmlRootElement.class);
            if(annotation != null){
                rootName = annotation.name();
            }
            if(rootName == null || rootName.equals("")){
                rootName = clasz.getSimpleName();
            }
        }
        
        //添加根节点   
        if(root.equals("") || root == null){
            root = rootName + "s";
        }
        sb.append("<"+ root  +">");
        //获得实体类的所有属性   
        //Field[] properties = clasz.getDeclaredFields();
        //递归实体;
        for (T t : entityPropertys) {
            String objToxml = objToxml(t,rootName);
            sb.append(objToxml);
        }
        sb.append("</"+ root  +">");
        return sb.toString();
        
    }
    
    public static String mapToxml(Map map, String rootName) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        StringBuffer sb = new StringBuffer();
        if(rootName == null || rootName.equals("")){
            rootName = "Map";
        }
        sb.append("<"+ rootName +">");
        Set keySet = map.keySet();
        for(Object key:keySet){
            Object value = map.get(key);
            if(value instanceof Date){
                Date date = (Date) value;
                String dateStr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);
                sb.append("<"+ key.toString() +">");
                sb.append(dateStr);
                sb.append("</"+ key.toString() +">");
                continue;
            }
            if(!(value instanceof Byte | value instanceof Short | 
                    value instanceof Integer | value instanceof Long | value instanceof Float |
                    value instanceof Double | value instanceof Character |
                    value instanceof Boolean | value instanceof String)){
                String objToxml = objToxml(value,null);
                sb.append("<"+ key.toString() +">");
                sb.append(objToxml);
                sb.append("</"+ key.toString() +">");
                continue;
            }
            sb.append("<"+ key.toString() +">");
            sb.append(value.toString());
            sb.append("</"+ key.toString() +">");
        }
        sb.append("</"+ rootName +">");
        return sb.toString();
    }
    
    public static int count(String text,String sub){
        int count =0, start =0;
        while((start=text.indexOf(sub,start))>=0){
            start += sub.length();
            count ++;
        }
        return count;
    }
    
    public static void main(String[] args) {
        
        
        int[] i = new int[]{1,2,3};
        byte[] b = new byte[]{'a','b','c'};
        TestEntitty entitty = new TestEntitty("AA", 1, i, b);
        try {
            String xml = XMLutil.objToxml(entitty,null);
            System.out.println(xml);
        } catch (NoSuchMethodException | SecurityException
                | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}
 

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值