Java读取XML文件(1)

4 篇文章 0 订阅

Java读取XML文件(1)

ReadXml.java

package Read;

import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

//------------------------------------------------
//----------@author River(赵振江)2015-4-22------------
//------------------------------------------------
public class ReadXml {
    public Document loadXml(String file) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(file);
            return document;

        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }


    public ArrayList<String> read(Node node) {
        ArrayList<String> arrList = new ArrayList<String>();
        return read(node, arrList);
    }

    private ArrayList<String> read(Node node, ArrayList<String> arrList) {
        if (node.getNodeType() == node.ELEMENT_NODE)
            arrList.add(node.getNodeName());
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            read(list.item(i), arrList);
        }
        return arrList;
    }

    public static void main(String[] args) {
        ReadXml readXml = new ReadXml();
        Document doc = readXml.loadXml("class.xml");
        ArrayList<String> list = readXml.read(doc);
        for (String str : list) {
            System.out.println(str);
        }
    }

}

class.xml

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


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值