java教程

java dom4j加载xml文件和解析的小Demo

位置:首页 > java教程 > java技巧,2015-04-27
java dom4j加载xml文件和解析的小Demo
package xml;
 
import java.io.File;
import java.util.Iterator;
 
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
 
public class TestXml {
    public Document loadXml(String filename){
        Document doc = null;
        SAXReader reader = new SAXReader();
        try {
            doc = reader.read(new File(filename));
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return doc;
    }
    public void parseXml(Document doc){
        Element root = doc.getRootElement();
        //枚举根节点下所有子节点
        for(Iterator<?> it = root.elementIterator(); it.hasNext();){
            System.out.println("----------");
            Element element = (Element) it.next();
            System.out.println(element.getName());
            //读取子节点中的属性信息
            for(Iterator<?> ia = element.elementIterator();ia.hasNext();){
                Element sonElement = (Element) ia.next();
                System.out.println(sonElement.getName() + ":" + sonElement.getData());
            }
        }
         
         
    }
    public static void main(String[] args){
        String filename = "student.xml";
        @SuppressWarnings("unused")
        Document doc = null;
        TestXml xml = new TestXml();
        doc = xml.loadXml(filename);
        xml.parseXml(doc);
         
    }
    }
student.xml
<students>
 
    <student>
    <name>Tom</name>
    <gender>male</gender>
    <age>24</age>
    </student>
     
    <student>
    <name>张三</name>
    <gender>男</gender>
    <age>27</age>
    </student>
     
</students>

TAGS:java解析xml文件

猜你喜欢

NewHot