xml文件简单读取,循环遍历

xml文件的简单读取出来生成dom4j.Document对象树,循环遍历获取节点

例子:

import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Dom4jText {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        try {
            //创建解析器
            SAXReader saxReader=new SAXReader();
            //通过解析器将xml读取到内存中,生成对象树
            Document document=saxReader.read("conf/student.xml");
            //获取根节点
            Element root=document.getRootElement();
            //遍历根节点
            for(Iterator<Element> rootlter=root.elementIterator();rootlter.hasNext();){
                Element student=rootlter.next();
                for(Iterator<Element> innerlter=student.elementIterator();innerlter.hasNext();){
                    Element innerElt=innerlter.next();
                    String name=innerElt.getName();
                    String value=innerElt.getStringValue();
                    System.out.println("name========="+name+"======value========="+value);
                }
                System.out.println("-------------------------------");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

程序用到xml:

<?xml version="1.0" encoding="UTF-8"?>
<students>
    <student>
        <name>张三</name>
        <age>11</age>
        <adress>浙江省是打发斯蒂芬二人11</adress>
    </student>
    <student>
        <name>李四</name>
        <age>22</age>
        <adress>浙江省是打发斯蒂芬二人22</adress>
    </student>
    <student>
        <name>王二麻子</name>
        <age>33</age>
        <adress>浙江省是打发斯蒂芬二人33</adress>
    </student>
</students>

 

点赞