Java读取XML文件(2)读取属性

4 篇文章 0 订阅

Java读取XML文件(2)读取属性

读取属性 
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>
</班级>

  
  

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值