java解析xml之dom解析xml示例分享
package com.test;
import java.io.file;
import java.util.arraylist;
import java.util.list;
import javax.xml.parsers.documentbuilder;
import javax.xml.parsers.documentbuilderfactory;
import org.w3c.dom.document;
import org.w3c.dom.element;
import org.w3c.dom.node;
import org.w3c.dom.nodelist;
public class domxml {
public static void main(string[] args) {
try {
file file = new file("e:/people.xml");
documentbuilderfactory factory = documentbuilderfactory.newinstance();
documentbuilder builder = factory.newdocumentbuilder();
document document = builder.parse(file);
element element = document.getdocumentelement();
list<people> peoplelist = new arraylist<people>();
nodelist peoplenodes = element.getelementsbytagname("people");
for(int i=0;i<peoplenodes.getlength();i++){
people people = new people();
element peopleelement = (element) peoplenodes.item(i);
people.setid(peopleelement.getattribute("id"));
nodelist childpeoplenodes = peopleelement.getchildnodes();
for(int j=0;j<childpeoplenodes.getlength();j++){
//dom解析时候注意子节点前面的空格也会被解析
if(childpeoplenodes.item(j) instanceof element){
element childpeopleelement = (element) childpeoplenodes.item(j);
if(childpeopleelement.getnodetype()==node.element_node){
if(childpeopleelement.getnodename().equals("name")){
people.setenglishname(childpeopleelement.getattribute("en"));
people.setname(childpeopleelement.gettextcontent());
}
else if(childpeopleelement.getnodename().equals("age")){
people.setage(childpeopleelement.gettextcontent());
}
}
}
}
peoplelist.add(people);
}
for(people people : peoplelist){
system.out.println(people.getid()+"\t"+people.getname()+"\t"+people.getenglishname()+"\t"+people.getage());
}
} catch (exception e) {
// todo 自动生成的 catch 块
e.printstacktrace();
}
}
}