Java读取XML文件读取属性

来源:互联网 发布:真空淬火油数据 编辑:程序博客网 时间:2024/05/21 18:45

读取属性 
ReadXml.java

。。。public static void showElem(NodeList nl) {        for (int i = 0; i < nl.getLength(); i++) {            Node n = nl.item(i);// 得到父节点            if (n.hasChildNodes()) {                NamedNodeMap attributes = n.getAttributes(); // 遍历节点所有属性如<dbstore                                                                // single="false"                                                                // att="tta">                // System.out.println(attributes.getLength());                for (int j = 0; j < attributes.getLength(); j++) {                    Node attribute = attributes.item(j);                    // 得到属性名                    String attributeName = attribute.getNodeName();                    System.out.println("属性名:" + attributeName);                    // 得到属性值                    String attributeValue = attribute.getNodeValue();                    System.out.println("属性值:" + attributeValue);                }// 打印出结果属性名:att属性值:tta属性名:single属性值:false            }            // 子节点            NodeList childList = n.getChildNodes();            for (int x = 0; x < childList.getLength(); x++) {                Node childNode = childList.item(x);                // 判断取出的值是否属于Element元素,目的是过滤掉                if (childNode instanceof Element) {                    // 得到子节点的名字                    String childNodeName = childNode.getNodeName();                    System.out.println("子节点名:" + childNodeName);                    // 得到子节点的值                    String childNodeValue = childNode.getTextContent();                    System.out.println("子节点值:" + childNodeValue);                }            }            showElem(n.getChildNodes());// 递归        }

class.xml

<?xml version="1.0" encoding="utf-8"?><班级>    <学生 id="a01">        <名字>周星驰</名字>        <年龄>23</年龄>        <介绍>学习刻苦</介绍>    </学生>    <学生 id="a02">        <名字>林青霞</名字>         <年龄>32</年龄>        <介绍>是一个好学生</介绍>    </学生>        <学生2 id="a03">        <名字>林青霞</名字>         <年龄>32</年龄>        <介绍>是一个好学生</介绍>    </学生2></班级>