Java读取xml工具类

xml工具类

自定义注解IXml

import java.lang.annotation.*;
/**
 * @ClassName: IXml
 * @Description: 注意:当前判断新建节点映射对象是根据类成员变量所有标注当前注解的字段值都不为null,
 * 所以:
 * 一 :所有nodeName都必须存在于xml文件中(区分大小写)
 * 二 :所有相同node节点和attributeName都必须相同,个数都保持一致
 * @1"<Code curCode="21000090000000011001" packLayer="3" flag="0" />"
 * @2“<Code curCode="21000080000000019897" packLayer="2" flag="0"  parentCode="21000090000000011001"/>”
 * 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 <T>
     * @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 <T>
     */
    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 <T>
     * @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文件

<?xml version="1.0" encoding="utf-8"?>
<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>10</Count>
	          <Money>100</Money>
	        </Detail>
		    <Detail>
	           <GoodeName>香蕉</GoodeName>
	           <Count>20</Count>
	           <Money>100</Money>
	       </Detail>
		   <Detail>
	           <GoodeName>橘子</GoodeName>
	           <Count>30</Count>
	           <Money>100</Money>
	       </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));
    }
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
package com.hexiang.utils; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * 本类是专门解析XML文件的,主要用于为系统读取自己的配置文件时提供最方便的解析操作 * @author HX * */ public class XmlManager { /** * 得到某节点下某个属性的值 * @param element 要获取属性的节点 * @param attributeName 要取值的属性名称 * @return 要获取的属性的值 * @author HX_2010-01-12 */ public static String getAttribute( Element element, String attributeName ) { return element.getAttribute( attributeName ); } /** * 获取指定节点下的文本 * @param element 要获取文本的节点 * @return 指定节点下的文本 * @author HX_2010-01-12 */ public static String getText( Element element ) { return element.getFirstChild().getNodeValue(); } /** * 解析某个xml文件,并在内存中创建DOM树 * @param xmlFile 要解析XML文件 * @return 解析某个配置文件后的Document * @throws Exception xml文件不存在 */ public static Document parse( String xmlFile ) throws Exception { // 绑定XML文件,建造DOM树 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document domTree = db.parse( xmlFile ); return domTree; } /** * 获得某节点下的某个子节点(指定子节点名称,和某个属性的值) * 即获取parentElement下名字叫childName,并且属性attributeName的值为attributeValue的子结点 * @param parentElement 要获取子节点的那个父节点 * @param childName 要获取的子节点名称 * @param attributeName 要指定的属性名称 * @param attributeValue 要指定的属性的值 * @return 符合条件的子节点 * @throws Exception 子结点不存在或有多个符合条件的子节点 * @author HX_2008-12-01 */ public static Element getChildElement( Element parentElement, String childName, String attributeName, String attributeValue ) throws Exception { NodeList list = parentElement.getElementsByTagName( childName ); int count = 0; Element curElement = null; for ( int i = 0 ; i < list.getLength() ; i ++ ) { Element child = ( Element )list.item( i ); String value = child.getAttribute( attributeName ); if ( true == value.equals( attributeValue ) ) { curElement =

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值