dom4j结合Xpath实现java对象和xml文件之间相互转化

1.目标

提供一个工具类,实现xml和java实体类相互转化

  1. 将xml文件的数据能够自动解析到对应的实体类中
  2. 根据java实体,自动生成相应的xml文件

2.实现

1.导入jar表
 <dependency>
     <groupId>org.projectlombok</groupId>
     <artifactId>lombok</artifactId>
     <version>1.18.20</version>
 </dependency>
 <dependency>
     <groupId>org.dom4j</groupId>
     <artifactId>dom4j</artifactId>
     <version>2.1.3</version>
 </dependency>
 <!-- Xpath解析-->
 <dependency>
     <groupId>jaxen</groupId>
     <artifactId>jaxen</artifactId>
     <version>1.1.6</version>
 </dependency>
2.代码实现
  1. xml转化的样例
<?xml version="1.0" encoding="UTF-8" ?>
<root>
	<head>
		<description>1</description>
		<detail>
			<date>2022-12-17</date>
			<version>2.0</version>
		</detail>
	</head>
	<body>
		<person>
			<id>1</id>
			<name>张三</name>
			<age>18</age>
			<height>18.8</height>
			<hobby>
				<order>1</order>
				<dec>篮球</dec>
			</hobby>
			<hobby>
				<order>2</order>
				<dec>足球</dec>
			</hobby>
			<hobby>
				<order>3</order>
				<dec>乒乓球</dec>
			</hobby>
			<score>12.8</score>
			<score>13.2</score>
		</person>
	</body>
</root>
  1. 自定义转化的两个注解
package annotation;

import java.lang.annotation.*;

/**
 * @description: 用在xml对应的实体类上,主要是用来指定根目录的
 * @author: 
 * @date: 2022/12/16 20:50
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface XmlClassDescription {
    String path() default "root"; // 指定xml文件的根目录
}
package annotation;

import java.lang.annotation.*;

/**
 1. @description: 自定义一个注解,用于指定属性对应xml上面的标签,且在运行时有效
 2. @author: 
 3. @date: 2022/12/16 19:45
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface XmlFiledDescription {
     String tagName(); // 指定xml对应的标签名
     boolean subTag() default false; // 是否有子标签,false代表没有,true代表有
     String format() default ""; // 指定数据的格式,时间类型的时候需要指定
     boolean isList () default false; // 标记当前标签是否有多个
     int order() default 0; // 在将java对象转化成xml文件时决定顺序,order越小在前面
}
  1. 编写对应的java实体类
/**
 * @description:
 * @author:
 * @date: 2022/12/16 19:51
 */
@XmlClassDescription
@Data
@ToString
public class MyDocument {

    @XmlFiledDescription(tagName ="head",subTag = true, order = 2)
    private Header header;

    @XmlFiledDescription(tagName ="body",subTag = true, order = 4)
    private Body body;
}

/**
 * @description:
 * @author: 
 * @date: 2022/12/16 19:37
 */
//@XmlClassDescription(path = "head")
@Data
@ToString
public class Header {
    @XmlFiledDescription(tagName ="description")
    private String description;

    @XmlFiledDescription(tagName ="detail",subTag = true)
    private Detail detail;
}
/**
 * @description:
 * @author: 
 * @date: 2022/12/16 19:39
 */
@Data
@ToString
public class Detail {
    @XmlFiledDescription(tagName ="date", format = "yyyy-MM-dd")
    private Date date;

    @XmlFiledDescription(tagName ="version")
    private String version;
}
/**
 * @description:
 * @author: 
 * @date: 2022/12/16 19:52
 */
@Data
@ToString
public class Body {
    @XmlFiledDescription(tagName = "person",subTag = true)
    private Person person;
}

/**
 * @description:
 * @author: 
 * @date: 2022/12/16 19:40
 */
@Data
@ToString
public class Person {
    @XmlFiledDescription(tagName ="name", order = 2)
    private String name;

    @XmlFiledDescription(tagName ="id", order = 1)
    private int id;

    @XmlFiledDescription(tagName ="age", order = 3)
    private int age;

    @XmlFiledDescription(tagName ="height", order = 4)
    private double height;

    @XmlFiledDescription(tagName ="hobby",subTag = true, isList = true, order = 6)
    private List<Hobby> hobbies;

    @XmlFiledDescription(tagName ="score", isList = true, order = 5)
    private List<Double> scores;
}

/**
 1. @description:
 2. @author: 
 3. @date: 2022/12/16 19:41
 */
@Data
@ToString
public class Hobby {
    @XmlFiledDescription(tagName = "order")
    private String order;
    @XmlFiledDescription(tagName = "dec")
    private String description;
}
  1. 工具类实现具体步骤
/**
 5. @description: 提供一个xml和java实体类相互转化的工具类
 6. @author: 
 7. @date: 2022/12/16 19:57
 */
public class XmlUtils {
    public static final String ROOT_PATH = "//";
    public static final String SUB_PATH = "./";
    /**
     * 该方法主要是将xml文件解析的字符串值转化成相关类型数据(感觉写的不好,暂时这样先实现)
     *
     * @param value tag标签里面解析的值
     * @param tClass 标签对应实体的Class
     * @param format 转化格式
     * @return 返回对应的数据类型
     */
    private static Object transferData(String value, Class tClass, String format) {
        String name = tClass.getSimpleName();
        try {
            switch (name) {
                case "Integer":
                case "int":
                    return Integer.valueOf(value);
                case "Double":
                case "double":
                    return Double.valueOf(value);
                case "Float":
                case "float":
                    return Float.valueOf(value);
                case "Byte":
                case "byte":
                    return Byte.valueOf(value);
                case "Short":
                case "short":
                    return Short.valueOf(value);
                case "Long":
                case "long":
                    return Long.valueOf(value);
                case "Character":
                case "char":
                    return value.charAt(0);
                case "Boolean":
                case "boolean":
                    return Boolean.valueOf(value);
                case "Date":
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
                    Date parse = simpleDateFormat.parse(value);
                    return parse;
                default:
                    return value;
            }
        } catch (Exception e) {
            throw new DataFormatException(value + "数据转化异常,请核对");
        }
    }

    /**
     * 该方法提供主要是为了处理java转xml文件时日期类型的处理(需要后面再补充)
     *
     * @param value 需要转化的值
     * @param format 转化的格式
     * @return 返回转化的字符串数据
     */
    private static String transferString(Object value, String format) {
        if (format.length() == 0) {
            return String.valueOf(value);
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        String transData = simpleDateFormat.format(value);
        return transData;
    }

    /**
     * 详细的转化过程,采用递归方式去进行
     *
     * @param parentNode 父标签节点
     * @param clazz 父标签对应当前实体的Class
     * @param t 父标签对应的实体(未赋值)
     * @param <T> 泛型
     * @return 返回构建的实体对象(赋值)
     */
    private static <T> T handle(Node parentNode, Class<T> clazz, T t){
        // 获取当前对象的所有属性
        Field[] fields = clazz.getDeclaredFields();
        Arrays.stream(fields).forEach(field -> {
            field.setAccessible(true);

            // 获取属性的XmlFiledDescription注解
            XmlFiledDescription xmlFiled = field.getDeclaredAnnotation(XmlFiledDescription.class);

            // 获取当前属性对应xml的标签名
            String tagName = xmlFiled.tagName();

            // 获取数据格式
            String format = xmlFiled.format();

            // 获取是否是一个集合
            boolean isList = xmlFiled.isList();

            // 判断当前属性是否有子标签
            boolean isSubTag = xmlFiled.subTag();
            Object value = null;
            if (isList) {
                try {
                    ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
                    Class actualTypeArgument = (Class) parameterizedType.getActualTypeArguments()[0];
                    List<Node> nodes = parentNode.selectNodes(SUB_PATH + tagName);

                    if (isSubTag) {
                        Object instance = actualTypeArgument.newInstance();
                        value = nodes.stream()
                                .map(node -> handle(node, actualTypeArgument, instance))
                                .collect(Collectors.toList());
                    } else {
                        value = nodes.stream()
                                .map(node -> transferData(node.getText(), actualTypeArgument, format))
                                .collect(Collectors.toList());
                    }
                    field.set(t, value);
                } catch (InstantiationException e) {
                    throw new DataFormatException(clazz + "获取实例失败,请提供无参构造");
                } catch (IllegalAccessException e) {
                    throw new DataFormatException(clazz + "获取实例失败,访问权限不足");
                }
            } else {
                try {
                    // 获取当前标签
                    Node currentNode = parentNode.selectSingleNode(SUB_PATH + tagName);
                    if (isSubTag) {
                        Class aClass = field.getType();
                        Object instance = aClass.newInstance();
                        value = handle(currentNode, aClass, instance);
                    } else {
                        value = transferData(currentNode.getText(), field.getType(), format);
                    }
                    field.set(t, value);
                } catch (InstantiationException e) {
                    throw new DataFormatException(clazz + "获取实例失败,请提供无参构造");
                } catch (IllegalAccessException e) {
                    throw new DataFormatException(clazz + "获取实例失败,访问权限不足");
                }
            }
        });
        return t;
    }

    /**
     *  详细的构建过程,采用递归的方式来构建
     *
     * @param instance 工厂示例,用于创建元素
     * @param parentElement 父标签元素
     * @param object 父标签对应java实体对象
     */
    private static void build(DocumentFactory instance, Element parentElement, Object object) {
        Class aClass = object.getClass();
        Field[] fields = aClass.getDeclaredFields();
        Arrays.stream(fields).sorted((field1, field2) -> {
            // 将属性按XmlFiledDescription的order进行排序
            field1.setAccessible(true);
            field2.setAccessible(true);
            XmlFiledDescription xmlFiled1 = field1.getDeclaredAnnotation(XmlFiledDescription.class);
            XmlFiledDescription xmlFiled2 = field2.getDeclaredAnnotation(XmlFiledDescription.class);
            return xmlFiled1.order() - xmlFiled2.order();
        }).forEach(field -> {
            field.setAccessible(true);
            XmlFiledDescription xmlFiled = field.getDeclaredAnnotation(XmlFiledDescription.class);

            // 获取标签名
            String tagName = xmlFiled.tagName();

            // 获取转化类型(针对时间类型处理)
            String format = xmlFiled.format();

            // 判断是否有子标签
            boolean isSubTag = xmlFiled.subTag();

            // 判断是否是一个集合
            boolean isList = xmlFiled.isList();
            Object currentObject = null;
            try {
                currentObject = field.get(object);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            if (isList) {
                List<Object> currentList = (List<Object>) currentObject;
                if (isSubTag) {
                    currentList.stream().forEach(item -> {
                        Element currentElement = instance.createElement(tagName);
                        parentElement.add(currentElement);
                        build(instance, currentElement, item);
                    });
                } else {
                    currentList.stream().forEach(item -> {
                        Element currentElement = instance.createElement(tagName);
                        String value = transferString(item, format);
                        currentElement.setText(value);
                        parentElement.add(currentElement);
                    });
                }
            } else {
                if (isSubTag) {
                    Element currentElement = instance.createElement(tagName);
                    parentElement.add(currentElement);
                    build(instance, currentElement, currentObject);
                } else {
                    Element currentElement = instance.createElement(tagName);
                    String value = transferString(currentObject, format);
                    currentElement.setText(value);
                    parentElement.add(currentElement);
                }
            }
        });
    }

    /**
     * 将xml文件转化成对应的实体类
     *
     * @param filePath xml文件路径
     * @param clazz 对应实体的Class
     * @param <T> 泛型
     * @return 返回赋值的java实体
     */
    public static <T> T xml2Object(String filePath, Class<T> clazz) {
        SAXReader saxReader = new SAXReader();
        try {
            // 获取xml的document
            Document document = saxReader.read(Dom4jXPath.class.getResource(filePath));

            // 获取当前类的注解
            XmlClassDescription declaredAnnotation = clazz.getDeclaredAnnotation(XmlClassDescription.class);

            // 获取xml的根标签名称(从对应的实体类上自定义注解找)
            Optional.ofNullable(declaredAnnotation)
                    .orElseThrow(() -> new DataFormatException("获取xml文件的根根标签名失败"));
            String path = declaredAnnotation.path();
            Node rootNode = document.selectSingleNode(ROOT_PATH + path);
            return handle(rootNode, clazz, clazz.newInstance());
        } catch (InstantiationException e) {
            throw new DataFormatException(clazz + "获取实例失败,请提供无参构造");
        } catch (IllegalAccessException e) {
            throw new DataFormatException(clazz + "获取实例失败,访问权限不足");
        } catch (DocumentException e) {
            throw new DataFormatException(filePath + "获取文件失败,请核对");
        }
    }

    /**
     *  该方法是将java的实体对象转化成xml文件
     *
     * @param filePath 文件名
     * @param object 实体对象
     * @param <T> 泛型
     */
    public static <T> void object2Xml(String filePath, T object) {
        XMLWriter xmlWriter = null;
        try {
            DocumentFactory instance = DocumentFactory.getInstance();
            Document document = instance.createDocument();
            Class aClass = object.getClass();

            // 设置根标签
            XmlClassDescription xmlClass =
                    (XmlClassDescription) aClass.getDeclaredAnnotation(XmlClassDescription.class);
            String rootPath = xmlClass.path();
            Element rootElement = instance.createElement(rootPath);
            document.setRootElement(rootElement);

            // 递归创建整个xml文档
            build(instance, rootElement, object);

            // 将生成的document写入到指定的文件中去
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("UTF-8");
            xmlWriter = new XMLWriter(new FileWriter(SUB_PATH + filePath), format);
            xmlWriter.write(document);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                xmlWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  1. 测试数据
   public static void main(String[] args) throws IOException {
        MyDocument myDocument = XmlUtils.xml2Object("/test.xml", MyDocument.class);
        System.out.println(myDocument);

//        test2();

    }

    public static void test2() throws IOException {
        MyDocument myDocument = new MyDocument();
        Detail detail = new Detail();
        detail.setDate(new Date());
        detail.setVersion("3.0");
        Header header = new Header();
        header.setDescription("cs");
        header.setDetail(detail);
        Person person = new Person();
        person.setId(1);
        person.setAge(18);
        person.setHeight(78.23);
        person.setName("zhangsan");
        ArrayList<Double> list = new ArrayList<>();
        list.add(12.3);
        list.add(13.7);
        ArrayList<Hobby> list1 = new ArrayList<>();
        Hobby hobby = new Hobby();
        hobby.setDescription("ca1");
        hobby.setOrder("222");
        Hobby hobby1 = new Hobby();
        hobby1.setDescription("ca2");
        hobby1.setOrder("333");
        list1.add(hobby);
        list1.add(hobby1);
        person.setHobbies(list1);
        person.setScores(list);
        Body body = new Body();
        body.setPerson(person);
        myDocument.setBody(body);
        myDocument.setHeader(header);
        XmlUtils.object2Xml("call.xml",myDocument);
    }
  1. 生成的call.xml结果如下:
<?xml version="1.0" encoding="UTF-8"?>

<root>
  <head>
    <description>cs</description>
    <detail>
      <date>2022-12-18</date>
      <version>3.0</version>
    </detail>
  </head>
  <body>
    <person>
      <id>1</id>
      <name>zhangsan</name>
      <age>18</age>
      <height>78.23</height>
      <score>12.3</score>
      <score>13.7</score>
      <hobby>
        <order>222</order>
        <dec>ca1</dec>
      </hobby>
      <hobby>
        <order>333</order>
        <dec>ca2</dec>
      </hobby>
    </person>
  </body>
</root>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值