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

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

程序员文章站 2024-02-21 13:28:04
复制代码 代码如下: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.list;

import org.jdom.document;
import org.jdom.element;
import org.jdom.input.saxbuilder;

public class jdomxml {

    public static void main(string[] args) {
        file file = new file("e:/people.xml");
        saxbuilder builder = new saxbuilder(); 
        try { 
            document document = builder.build(file); 
            element root = document.getrootelement(); 
            list<element> list = root.getchildren(); 
            list<people> peoples = new arraylist<people>(); 
            people people = null;  
            for (element peopleelement : list) { 
                people = new people(); 
                if(null != peopleelement.getattribute("id")){
                    people.setid(peopleelement.getattribute("id").getvalue()); 
                }
                list<element> childpeopleelements = peopleelement.getchildren(); 
                for (element childpeopleelement : childpeopleelements) { 
                    if ("name".equals(childpeopleelement.getname())) { 
                        people.setenglishname(childpeopleelement.getattributevalue("en"));
                        people.setname(childpeopleelement.gettext()); 
                    } 
                    else if ("age".equals(childpeopleelement.getname())) { 
                        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) { 
            e.printstacktrace(); 
        } 

    }

}