欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java解析xml之dom4j解析xml示例分享

程序员文章站 2024-02-21 13:20:16
复制代码 代码如下:package com.test; import java.io.file;import java.util.arraylist;import jav...

复制代码 代码如下:

package com.test;

import java.io.file;
import java.util.arraylist;
import java.util.iterator;
import java.util.list;

import org.dom4j.document;
import org.dom4j.element;
import org.dom4j.io.saxreader;

public class dom4jxml {

    public static void main(string[] args) {
        saxreader saxreader = new saxreader();
        file file = new file("e:/people.xml");

        try {
            document document = saxreader.read(file);
            element root = document.getrootelement();
            list<people> peoples = new arraylist<people>();
            for (iterator iterator = root.elementiterator(); iterator.hasnext();) {
                people people = new people();
                element peopleelement = (element) iterator.next();
                people.setid(peopleelement.attribute("id").getvalue());
                for (iterator childiterator = peopleelement.elementiterator(); childiterator.hasnext();) {
                    element childpeopleelement = (element) childiterator.next();
                    if (childpeopleelement.getname().equals("name")) {
                        people.setenglishname(childpeopleelement.attribute("en").getvalue());
                        people.setname(childpeopleelement.gettext());
                    } else if (childpeopleelement.getname().equals("age")) {
                        people.setage(childpeopleelement.gettext());
                    }
                }
                peoples.add(people);
            }

            for (people p : peoples) { 
                system.out.println(p.getid()+"\t"+p.getname()+"\t"+p.getenglishname()+"\t"+p.getage()); 
            } 

        } catch (exception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }

    }
}