Java读取xml工具类

xml工具类

自定义注解IXml

import java.lang.annotation.*;
/**
 * @ClassName: IXml
 * @Description: 注意:当前判断新建节点映射对象是根据类成员变量所有标注当前注解的字段值都不为null,
 * 所以:
 * 一 :所有nodeName都必须存在于xml文件中(区分大小写)
 * 二 :所有相同node节点和attributeName都必须相同,个数都保持一致
 * @1""
 * @2“”
 * 1比2少一个 parentCode  ,造成只读取了2这一条数据,可以给1 添加一个parentCode=“” 空字符串即可
 * 三:如果不确定某个节点或属性一定有值,标注该注解的成员变量类型用String
 * @Date: 2023/3/20 14:24
 * @author: ph9527
 * @version: 1.0
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface IXml {
    /**
     * 当前字段所属xml的标签名称
     *
     * @return
     * @注意1: 默认取值为标签的内容,如果是标签的属性值,添加“attributeName”
     * @注意2: 如果不需要attribute的信息不要填写 (不要填写 不要填写 不要填写) attributeName
     */
    String nodeName();

    /**
     * 标签的属性名称
     *
     * @return
     * @注意1: 当该字段的值为xml中的属性描述的值时,该属性“attributeName”必填
     * @注意2: 如果不需要该值,不要填写 不要填写 不要填写 不要填写
     */
    String attributeName() default "";

    /**
     * 是否子集,当为true时,nodeName可以填写任何值,
     *
     * @return
     */
    boolean isSon() default false;

    /**
     * 日期转换格式
     *
     * @return
     */
    String dateFormat() default "";

}

工具类 XmlUtils

package com.ph.xml;

import com.ph.xml.annotation.IXml;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: XmlUtils
 * @Description: TODO
 * @Date: 2023/3/20 14:24
 * @author: ph9527
 * @version: 1.0
 */
public class XmlUtils {


    /**
     * xml结构
     */
    static class NodeXml {
        //节点名称
        private String nodeName;
        //节点值
        private String nodeValue;

        //属性名称
        private List<Attribute> attributes;

        private List<NodeXml> sonXmlNodes;

    }

    /**
     * xml属性
     */
    static class Attribute {
        //属性名称
        private String attributeName;
        //属性值
        private String attributeValue;

    }

    /**
     * 实体类与xml映射
     */
    static class ClassNode {
        //node名称
        private String nodeName;

        //attribute名称
        private String attributeName;

        //class字段名称
        private String fieldName;

        //当前字段所在clazz
        private Class clazz;

        //父级class对象
        private Class parentClass;

        //节点级别
        private Integer level;

        //节点的值
        private String value;


        //true:当前类成员变量值为node的值;  false:当前成员变量值为所属node的attribute的值
        private Boolean isNode;

        private List<ClassNode> sons;
    }

    /**
     * 读取xml文件
     *
     * @param xmlFile
     * @param clazz
     * @param 
     * @return
     */
    public static <T> List<T> readXml(File xmlFile, Class<T> clazz) {
        List<T> data = new ArrayList<>();
        Document document = null;
        try {
            // 创建解析器工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            // 创建一个Document对象
            document = db.parse(xmlFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (document != null) {
            Element rootElement = document.getDocumentElement();
            //获取整个XML节点信息
            NodeXml nodeXml = getNodeXMlInfo(rootElement);
            //获取当前entity的所有注解@IXml的属性
            List<ClassNode> rs = new ArrayList<>();

            List<ClassNode> resourceClassNodes = getAllFieldMapForClass(clazz, null, rs, 0);

            if (nodeXml != null) {
                try {
                    setData(nodeXml, data, clazz, resourceClassNodes);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

        return data;
    }


    /**
     * 获取class与node的所有映射
     *
     * @param clazz
     * @param parentClass
     * @param rs
     * @param level
     * @return
     */
    private static List<ClassNode> getAllFieldMapForClass(Class clazz, Class parentClass, List<ClassNode> rs, Integer level) {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            IXml ixml = field.getAnnotation(IXml.class);
            if (null != ixml) {
                String fieldName = field.getName();
                ClassNode classnode = null;
                if (!ixml.isSon()) {
                    //不是子集
                    String nodeName = ixml.nodeName();
                    String attributeName = ixml.attributeName();
                    //如果ixml.attributeName为空则field的值为node 反之值为attribute的值
                    if (strIsNotBlank(attributeName)) {
                        // field的值为attribute的值
                        classnode = setClassNode(fieldName, nodeName, attributeName, false, clazz, parentClass, level);
                    } else {
                        // field的值为node的值
                        classnode = setClassNode(fieldName, nodeName, null, true, clazz, parentClass, level);
                    }
                } else {
                    level++;
                    //子集
                    classnode = setClassNodeSons(field, clazz, level);
                }

                if (classnode != null) {
                    rs.add(classnode);
                }
            }
        }
        return rs;
    }

    /**
     * 设置classNode子集
     *
     * @param field
     * @param parentClass
     * @param level
     * @return
     */
    private static ClassNode setClassNodeSons(Field field, Class parentClass, Integer level) {
        Class clazz = getGenericClassForList(field);
        ClassNode classNode = null;
        if (clazz != null) {
            List<ClassNode> classNodes = new ArrayList<>();
            List<ClassNode> classNodeSons = getAllFieldMapForClass(clazz, parentClass, classNodes, level);
            classNode = new ClassNode();
            classNode.sons = classNodeSons;
            classNode.fieldName = field.getName();
        }
        return classNode;
    }

    /**
     * 获取List的泛型类型
     *
     * @param field
     * @return
     */
    private static Class getGenericClassForList(Field field) {
        Class clazz = null;
        if (field.getType() == List.class) {
            Type genericType = field.getGenericType();
            if (genericType != null && genericType instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) genericType;
                clazz = (Class<?>) pt.getActualTypeArguments()[0];
            }
        }
        return clazz;
    }

    /**
     * 设置classNode信息
     *
     * @param fieldName
     * @param attributeName
     * @param isNode
     * @param clazz
     * @param parentClass
     * @param level
     * @return
     */
    private static ClassNode setClassNode(String fieldName, String nodeName, String attributeName, Boolean isNode, Class clazz, Class parentClass, Integer level) {
        ClassNode classNode = new ClassNode();
        classNode.fieldName = fieldName;
        classNode.attributeName = attributeName;
        classNode.nodeName = nodeName;
        classNode.isNode = isNode;
        classNode.clazz = clazz;
        classNode.parentClass = parentClass;
        classNode.level = level;
        return classNode;
    }

    /**
     * 设置值
     *
     * @param nodeXml
     * @param data
     * @param sourceClazz
     * @param resourceClassNodes
     * @param 
     */
    private static <T> void setData(NodeXml nodeXml, List<T> data, Class<T> sourceClazz, List<ClassNode> resourceClassNodes) throws Exception {
        //当前级别对象集
        List nowObjLevel = new ArrayList();

        //获取所有节点值
        List<ClassNode> classNodeValuesMapping = new ArrayList<>();
        getNodeValueToClassNodeValue(nodeXml, resourceClassNodes, classNodeValuesMapping);
        //添加一个null,多循环一次,添加最后一个对象到list
        classNodeValuesMapping.add(null);

        //初始当前对象
        Object nowObject = sourceClazz.newInstance();
        //添加第一个级别对象
        nowObjLevel.add(nowObject);
        //初始子集
        List sonList = getSonList(nowObject);

        if (classNodeValuesMapping.size() > 1) {
            for (ClassNode classNode : classNodeValuesMapping) {
                if (classNode != null) {

                    Class nodeClazz = classNode.clazz;
                    //检测当前对象是否填满
                    Boolean isFill = checkNowObjectIsFill(nowObject);
                    if (isFill) {
                        if (nowObject.getClass().getTypeName().equals(sourceClazz.getTypeName())) {
                            data.add((T) nowObject);
                        } else {
                            if (sonList != null) {
                                sonList.add(nowObject);
                            }
                        }

                        nowObject = nodeClazz.newInstance();

                        //当前级别
                        Integer nowLevel = classNode.level;
                        if ((nowLevel + 1) <= nowObjLevel.size()) {
                            nowObjLevel.set(nowLevel, nowObject);
                        } else {
                            nowObjLevel.add(nowObject);
                        }

                        //当前对象子集对象
                        Class parentClass = classNode.parentClass;
                        //查看当前对象的父级
                        if (parentClass != null) {
                            //当前父级对象
                            Object nowParentObj = findParentObj(parentClass, nowObjLevel);
                            sonList = getSonList(nowParentObj);
                        }

                    }

                    //填充属性
                    nodeValueToObject(classNode, classNode.value, nowObject);

                } else {
                    if (nowObject.getClass().getTypeName().equals(sourceClazz.getTypeName())) {
                        data.add((T) nowObject);
                    } else {
                        if (sonList != null) {
                            sonList.add(nowObject);
                        }
                    }
                }

            }
        }


    }

    /**
     * 获取当前对象的父级对象
     *
     * @param parentClass
     * @param nowObjLevel
     * @return
     */
    private static Object findParentObj(Class parentClass, List nowObjLevel) {
        String typeName = parentClass.getTypeName();
        for (Object obj : nowObjLevel) {
            if (obj.getClass().getTypeName().equals(typeName)) {
                return obj;
            }
        }
        return null;
    }

    /**
     * 获取当前对象有注解@IXml且isSon=true的list
     *
     * @param nowParentObj
     * @return
     */
    private static List getSonList(Object nowParentObj) throws Exception {
        Class clazz = nowParentObj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            IXml Ixml = field.getAnnotation(IXml.class);
            if (Ixml != null && Ixml.isSon()) {
                Object sonList = field.get(nowParentObj);
                if (sonList != null) {
                    return (List) sonList;
                } else {
                    List newSonList = new ArrayList<>();
                    field.set(nowParentObj, newSonList);
                    return newSonList;
                }

            }
        }
        return null;
    }

    /**
     * 获取所有字段的值
     *
     * @param nodeXml                当前节点
     * @param resourceClassNodes
     * @param classNodeValueMappings
     * @param 
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    private static <T> void getNodeValueToClassNodeValue(NodeXml nodeXml, List<ClassNode> resourceClassNodes, List<ClassNode> classNodeValueMappings) throws Exception {
        String nodeName = nodeXml.nodeName;
        List<ClassNode> classNodes = new ArrayList<>();
        findClassNodeByNodeName(nodeName, resourceClassNodes, classNodes);
        if (classNodes.size() > 0) {
            for (ClassNode classNode : classNodes) {
                String value = getValueFromXml(classNode, nodeXml);
                ClassNode newClassNode = new ClassNode();
                newClassNode.nodeName = classNode.nodeName;
                newClassNode.fieldName = classNode.fieldName;
                newClassNode.attributeName = classNode.attributeName;
                newClassNode.clazz = classNode.clazz;
                newClassNode.parentClass = classNode.parentClass;
                newClassNode.isNode = classNode.isNode;
                newClassNode.level = classNode.level;
                newClassNode.value = value;
                classNodeValueMappings.add(newClassNode);
            }
        }
        List<NodeXml> sonXmlNodes = nodeXml.sonXmlNodes;
        if (sonXmlNodes != null && sonXmlNodes.size() > 0) {
            for (NodeXml sonXmlNode : sonXmlNodes) {
                getNodeValueToClassNodeValue(sonXmlNode, resourceClassNodes, classNodeValueMappings);
            }

        }

    }

    /**
     * 填充值到当前对象
     *
     * @param classNode
     * @param value
     * @param nowObject
     */
    private static void nodeValueToObject(ClassNode classNode, String value, Object nowObject) {
        Field field = getFieldFromClassNode(classNode, nowObject);
        if (value != null && field != null) {
            try {
                field.setAccessible(true);
                Class<?> type = field.getType();
                if (type == Double.class || type == double.class) {

                    Double newValue = Double.valueOf(value);
                    field.set(nowObject, newValue);
                } else if (type == Long.class || type == long.class) {
                    Long newValue = Long.valueOf(value);
                    field.set(nowObject, newValue);
                } else if (type == Date.class) {
                    IXml iXml = field.getAnnotation(IXml.class);
                    if (iXml != null) {
                        String dateFormat = iXml.dateFormat();
                        if (strIsNotBlank(dateFormat)) {
                            SimpleDateFormat format = new SimpleDateFormat(dateFormat);
                            Date newValue = format.parse(value);
                            field.set(nowObject, newValue);
                        }
                    }
                } else if (type == Integer.class || type == int.class) {
                    Integer newValue = Integer.valueOf(value);
                    field.set(nowObject, newValue);
                } else {
                    field.set(nowObject, value);
                }


            } catch (IllegalAccessException | ParseException | IllegalArgumentException e) {
                throw new RuntimeException("属性:[" + classNode.fieldName + "]与value : " + value + " 类型转换异常  " + e);
            }

        }


    }

    /**
     * 获取需要设置值的字段
     *
     * @param classNode
     * @param nowObject
     * @return
     */
    private static Field getFieldFromClassNode(ClassNode classNode, Object nowObject) {
        String fieldName = classNode.fieldName;
        Class<?> clazz = nowObject.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.getName().equals(fieldName)) {
                return field;
            }
        }
        return null;
    }

    /**
     * 从xml获取值
     *
     * @param classNode
     * @param nodeXml
     * @return
     */
    private static String getValueFromXml(ClassNode classNode, NodeXml nodeXml) {
        Boolean isNode = classNode.isNode;
        if (isNode) {//field值为node的值
            return nodeXml.nodeValue;
        } else {//field值为node属性值
            String attributeName = classNode.attributeName;
            List<Attribute> attributes = nodeXml.attributes;
            for (Attribute attribute : attributes) {
                if (attribute.attributeName.equals(attributeName)) {
                    return attribute.attributeValue;
                }
            }
        }
        return null;
    }

    /**
     * 检测当前对象所有标有注解Ixml的属性都已赋值(子集属性除外)
     *
     * @param nowObject
     * @return
     */
    private static Boolean checkNowObjectIsFill(Object nowObject) throws Exception {
        Class nowClass = nowObject.getClass();
        Field[] fields = nowClass.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            IXml ixml = field.getAnnotation(IXml.class);
            if (ixml != null && !ixml.isSon()) {
                Object obj = field.get(nowObject);
                if (obj == null) {
                    return false;
                }
            }

        }
        return true;
    }


    /**
     * 根据nodeName查询ClassNode
     *
     * @param nodeName
     * @param resourceClassNodes
     * @param classNodes
     * @return
     */
    private static void findClassNodeByNodeName(String nodeName, List<ClassNode> resourceClassNodes, List<ClassNode> classNodes) {
        for (ClassNode classNode : resourceClassNodes) {
            if (classNode.sons == null) {
                //不是子集
                if (nodeName.equals(classNode.nodeName)) {
                    classNodes.add(classNode);
                }
            } else {
                //是子集
                findClassNodeByNodeName(nodeName, classNode.sons, classNodes);
            }
        }
    }


    /**
     * 获取整个xml节点的信息
     *
     * @param rootElement
     * @return
     */
    private static NodeXml getNodeXMlInfo(Element rootElement) {
        NodeXml nodeXml = null;
        if (rootElement != null) {
            nodeXml = new NodeXml();
            nodeXml.nodeName = rootElement.getNodeName();
            nodeXml.nodeValue = strIsNotBlank(rootElement.getNodeValue()) ? rootElement.getNodeValue() : "";
            NamedNodeMap attributes = rootElement.getAttributes();
            List<Attribute> attributeInfo = getAttributeInfo(attributes);
            nodeXml.attributes = attributeInfo;
            NodeList childNodes = rootElement.getChildNodes();
            if (childNodes != null && childNodes.getLength() > 0) nodeXml.sonXmlNodes = getSonNodeInfo(childNodes);

        }
        return nodeXml;
    }

    /**
     * 获取节点相关信息
     *
     * @param nodeList
     */
    private static List<NodeXml> getSonNodeInfo(NodeList nodeList) {
        List<NodeXml> nodeXmlList = new ArrayList<>();
        int nodeLength = nodeList.getLength();
        for (int i = 0; i < nodeLength; i++) {
            Node nodeItem = nodeList.item(i);
            String nodeName = nodeItem.getNodeName();
            if (checkNodeName(nodeName)) {
                NodeXml nodeXml = setNodeInfo(nodeItem);
                NodeList childNodes = nodeItem.getChildNodes();
                if (childNodes != null && childNodes.getLength() > 0) nodeXml.sonXmlNodes = getSonNodeInfo(childNodes);
                nodeXmlList.add(nodeXml);
            }

        }
        return nodeXmlList;
    }

    /**
     * 设置节点相关信息
     *
     * @param nodeItem
     * @return
     */
    private static NodeXml setNodeInfo(Node nodeItem) {
        NodeXml nodeXml = new NodeXml();
        nodeXml.nodeName = nodeItem.getNodeName();
        Node firstChild = nodeItem.getFirstChild();
        if (firstChild != null) {
            nodeXml.nodeValue = firstChild.getNodeValue();
        }
        //属性相关信息值设置
        NamedNodeMap attributes = nodeItem.getAttributes();
        List<Attribute> attributeList = getAttributeInfo(attributes);
        nodeXml.attributes = attributeList;
        return nodeXml;
    }

    /**
     * 获取属性相关信息
     *
     * @param attributes
     * @return
     */
    private static List<Attribute> getAttributeInfo(NamedNodeMap attributes) {
        List<Attribute> attributeList = new ArrayList<>();
        int attributeLength;
        if (attributes != null && (attributeLength = attributes.getLength()) > 0) {
            for (int j = 0; j < attributeLength; j++) {
                Node attributeNode = attributes.item(j);
                Attribute attribute = new Attribute();
                attribute.attributeName = attributeNode.getNodeName();
                attribute.attributeValue = strIsNotBlank(attributeNode.getNodeValue()) ? attributeNode.getNodeValue() : "";
                attributeList.add(attribute);
            }
        }
        return attributeList;
    }

    /**
     * 检测节点名称不为空
     *
     * @param nodeName
     * @return
     */
    private static Boolean checkNodeName(String nodeName) {
        return nodeName != null && nodeName.trim() != "" && !nodeName.trim().equals("#text");
    }

    /**
     * 检验字符串不为空
     *
     * @param str
     * @return
     */
    private static Boolean strIsNotBlank(String str) {
        return str != null && !str.trim().equals("");
    }

}


示例xml文件


<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="订单XML Schema-3.0.xsd" License="00120-100290-002">
  <Events version="3.0">
    <Event name="Order">
      <Order orderNo="D181101004" orderTime="2023-01-01" buyer="小明" moneyTotal="300">
        <OrderDetails>
           <Detail>
	          <GoodeName>芒果GoodeName>
	          <Count>10Count>
	          <Money>100Money>
	        Detail>
		    <Detail>
	           <GoodeName>香蕉GoodeName>
	           <Count>20Count>
	           <Money>100Money>
	       Detail>
		   <Detail>
	           <GoodeName>橘子GoodeName>
	           <Count>30Count>
	           <Money>100Money>
	       Detail>
	     OrderDetails>
      Order>
    Event>
  Events>
Document>

示例xml相关实体类—Order

import java.util.Date;
import java.util.List;

/**
 * @ClassName: Order
 * @Description: TODO
 * @Date: 2023/4/10 11:21
 * @author: ph9527
 * @version: 1.0
 */
public class Order {

    @IXml(nodeName = "Order", attributeName = "orderNo")
    private String orderNo;

    @IXml(nodeName = "Order", attributeName = "orderTime", dateFormat = "yyyy-MM-dd")
    private Date orderTime;

    @IXml(nodeName = "Order", attributeName = "buyer")
    private String buyer;

    @IXml(nodeName = "Order", attributeName = "moneyTotal")
    private Double moneyTotal;

    @IXml(nodeName = "这里名称随便写,或者空字符串都行", isSon = true)
    private List<OrderDetail> details;

    public Order(String orderNo, Date orderTime, String buyer, Double moneyTotal, List<OrderDetail> details) {
        this.orderNo = orderNo;
        this.orderTime = orderTime;
        this.buyer = buyer;
        this.moneyTotal = moneyTotal;
        this.details = details;
    }

    public Order() {
    }

    public String getOrderNo() {
        return orderNo;
    }

    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }

    public Date getOrderTime() {
        return orderTime;
    }

    public void setOrderTime(Date orderTime) {
        this.orderTime = orderTime;
    }

    public String getBuyer() {
        return buyer;
    }

    public void setBuyer(String buyer) {
        this.buyer = buyer;
    }

    public Double getMoneyTotal() {
        return moneyTotal;
    }

    public void setMoneyTotal(Double moneyTotal) {
        this.moneyTotal = moneyTotal;
    }

    public List<OrderDetail> getDetails() {
        return details;
    }

    public void setDetails(List<OrderDetail> details) {
        this.details = details;
    }

    @Override
    public String toString() {
        return "Order{" +
                "orderNo='" + orderNo + '\'' +
                ", orderTime=" + orderTime +
                ", buyer='" + buyer + '\'' +
                ", moneyTotal=" + moneyTotal +
                ", details=" + details +
                '}';
    }
}

示例xml相关实体类—OrderDetail

import java.util.Date;

/**
 * @ClassName: OrderDetail
 * @Description: TODO
 * @Date: 2023/4/10 11:25
 * @author: ph9527
 * @version: 1.0
 */
public class OrderDetail {

    @IXml(nodeName = "GoodeName")
    private String goodName;

    @IXml(nodeName = "Count")
    private Integer count;

    @IXml(nodeName = "Money")
    private Double money;

    public OrderDetail(String goodName, Integer count, Double money) {
        this.goodName = goodName;
        this.count = count;
        this.money = money;
    }

    public OrderDetail() {
    }

    public String getGoodName() {
        return goodName;
    }

    public void setGoodName(String goodName) {
        this.goodName = goodName;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "OrderDetail{" +
                "goodName='" + goodName + '\'' +
                ", count=" + count +
                ", money=" + money +
                '}';
    }
}

测试方法

    public static void main(String[] args) throws Exception {
        File file = new File("D:\\PH\\Desktop\\工作\\测试xml\\订单.xml");
        List<Order> relations = XmlUtils.readXml(file, Order.class);
        relations.stream().forEach(item -> System.out.println(item));
    }

你可能感兴趣的:(工具类,xml,java,jvm)