注解+反射+递归动态生成多层XML

发布时间:2020-07-31 02:22:18 作者:七羽燕
来源:网络 阅读:3851

1.首先我们先创建一个xml的帮助类,这个帮助类不许要任何属性,需要帮助实体类识别其他的成员实体类,代码如下:
注释xml帮助类

import java.lang.annotation.Documented;

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

/**

*

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.FIELD)

@Documented

public @interface XmlHelper {}

2.下面我们多创建几个实体类,并且使它们通过@XmlHelper的注解联系起来,代码如下:
import java.util.List;

/**

public class Child {

private String name;

private String age;

@XmlHelper

private List<ChildToChild> childToChilds;

@XmlHelper

private Child2 child2;

public Child2 getChild2() {

    return child2;

}

public void setChild2(Child2 child2) {

    this.child2 = child2;

}

public String getName() {

    return name;

}

public void setName(String name) {

    this.name = name;

}

public String getAge() {

    return age;

}

public void setAge(String age) {

    this.age = age;

}

public List<ChildToChild> getChildToChilds() {

    return childToChilds;

}

public void setChildToChilds(List<ChildToChild> childToChilds) {

    this.childToChilds = childToChilds;

}

}

/**

public class Child2 {

private String name;

private String age;

public String getName() {

    return name;

}

public void setName(String name) {

    this.name = name;

}

public String getAge() {

    return age;

}

public void setAge(String age) {

    this.age = age;

}

}

/**

public class ChildToChild {

private String name;

private String age;

public String getName() {

    return name;

}

public void setName(String name) {

    this.name = name;

}

public String getAge() {

    return age;

}

public void setAge(String age) {

    this.age = age;

}

}

/**

public class Parent {

private String name;

private String age;

@XmlHelper

private Child child;

@XmlHelper

private ParentToParent parentToParent;

public Child getChild() {

    return child;

}

public void setChild(Child child) {

    this.child = child;

}

public String getName() {

    return name;

}

public void setName(String name) {

    this.name = name;

}

public String getAge() {

    return age;

}

public void setAge(String age) {

    this.age = age;

}

public ParentToParent getParentToParent() {

    return parentToParent;

}

public void setParentToParent(ParentToParent parentToParent) {

    this.parentToParent = parentToParent;

}

}

/**

public class ParentToParent {

private String name;

private String age;

public String getName() {

    return name;

}

public void setName(String name) {

    this.name = name;

}

public String getAge() {

    return age;

}

public void setAge(String age) {

    this.age = age;

}

}

3.下面我们写一下xml的生成和测试类,代码如下:
xml生成和测试类

import java.beans.PropertyDescriptor;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.DocumentHelper;

import org.dom4j.Element;

import com.alibaba.fastjson.JSON;

/**

public class TestMain {

public static void main(String[] args) throws DocumentException {

    List<ChildToChild> childToChilds = new ArrayList<ChildToChild>();

    ChildToChild ctc = new ChildToChild();

    ctc.setAge("8");

    ctc.setName("ctc1");

    ChildToChild ctc2 = new ChildToChild();

    ctc2.setAge("8");

    ctc2.setName("ctc2");

    childToChilds.add(ctc);

    childToChilds.add(ctc2);

    Child2 c2 = new Child2();

    c2.setAge("c18");

    c2.setName("c2");

    Child c = new Child();

    c.setAge("18");

    c.setName("C");

    c.setChildToChilds(childToChilds);

    c.setChild2(c2);

    ParentToParent ptp = new ParentToParent();

    ptp.setAge("p48");

    ptp.setName("ptp");

    Parent p = new Parent();

    p.setAge("48");

// p.setName("P");

    p.setChild(c);

    p.setParentToParent(ptp);

//生成xml
Document doc = DocumentHelper.createDocument();

    Element root = doc.addElement("xml");

    Element eles = root.addElement("interface");

    eles.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");

    eles.addAttribute("xsi:schemaLocation", "http://www.chinatax.gov.cn/tirip/dataspec/interfaces.xsd");

    eles.addAttribute("version", "DZFP1.0");

    getbean(p, eles, "Child");

    String reqBody = "<?xml version='1.0' encoding='utf-8' ?>"

            + doc.getRootElement().asXML();

    System.out.println(reqBody);

    Document document=DocumentHelper.parseText(reqBody);

    Element r=document.getRootElement();

    Map<String, Object> map = ParseXml.getMap(r, r.nodeCount());

    System.out.println(JSON.toJSONString(map));

}

/**

 * 生成xml

 * @param o

 * @param root

 */

public static void getbean(Object o, Element root, String name) {

    Class<? extends Object> cls = o.getClass();

    try {

        // 得到自定义的属性

        Field[] fields = cls.getDeclaredFields();

        for (Field f : fields) {

            // 获取属性

            PropertyDescriptor pd = new PropertyDescriptor(f.getName(), cls);

            Method getMethod = pd.getReadMethod();// 获得get方法

            Object ob = getMethod.invoke(o);// 执行get方法返回一个Object

// System.out.println(f.getName() + ":" + f.getType().getName() + " = " + JSON.toJSONString(ob));

            XmlHelper xh = f.getAnnotation(XmlHelper.class);//获取带有@XmlHelper注解的实体

            if (xh != null) {

                if(name != null && !"".equals(name) && name.equals(o.getClass().getSimpleName())){

                    if(f.getType().getName().equals("java.util.List") && ((List)ob).size() > 0){

                        Element eles = root.addElement(f.getName());

                        eles.addAttribute("class", f.getName().substring(0, f.getName().length() - 1));//标签添加class属性

                        eles.addAttribute("size", ((List)ob).size() + "");//标签添加size属性

                        for(int i = 0; i < ((List)ob).size(); i++){

                            Object os = ((List)ob).get(i);

                            Element ele = eles.addElement(os.getClass().getSimpleName());//添加xml标签

                            getbean(os, ele, name);//递归 注解类继续解析

                        }

                    }else{

                        Element ele = root.addElement(f.getName());

                        ele.addAttribute("class", f.getName());//标签添加class属性

                        String getMeName = "get" + f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1);//构造set方法

                        Method actionMethod = cls.getDeclaredMethod(getMeName);

                        // 执行这个方法

                        Object obj = actionMethod.invoke(o);

                        getbean(obj, ele, name);//递归 注解类继续解析

                    }

                }else{

                    Element ele = root.addElement(f.getName());

                    String getMeName = "get" + f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1);//构造set方法

                    Method actionMethod = cls.getDeclaredMethod(getMeName);

                    // 执行这个方法

                    Object obj = actionMethod.invoke(o);

                    getbean(obj, ele, name);//递归 注解类继续解析

                }

            } else {

                if(ob != null){

                    root.addElement(f.getName()).addText(JSON.toJSONString(ob).replace("\"", ""));

                }else{

                    root.addElement(f.getName());

                }

            }

        }

    } catch (Exception e) {

    }

}

}

4.xml解析类
import java.util.HashMap;

import java.util.Map;

import org.dom4j.Document;

import org.dom4j.DocumentHelper;

import org.dom4j.Element;

import com.alibaba.fastjson.JSON;

/**

public class ParseXml {

public static Map<String, Object> getMap(Element e, int cnt){

    Map<String, Object> map = new HashMap<String, Object>();

    int count = cnt;

    for(int j = 0; j < count; j++){

        if(null != e.node(j).getName()){

            Element el = e.element(e.node(j).getName());

            if(el.getText() == null || "".equals(el.getText())){

                Map<String, Object> ma = getMap(el,el.nodeCount());

                map.put(e.node(j).getName(), ma);

            }else{

                map.put(el.getName(), el.getText());

            }

        }

    }

    return map;

}

}

推荐阅读:
  1. java 反射注解信息
  2. XML中XDocument与XmlDocument递归读取xml文件的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

注解 递归 反射

上一篇:【Tips篇】爬虫

下一篇:dubbo客户端版本选择

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》