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();
}
}
}
推荐阅读
-
java解析xml之dom解析xml示例分享
-
java使用dom4j解析xml配置文件实现抽象工厂反射示例
-
java 解析由String类型拼接的XML文件方法
-
通过dom4j解析xml字符串(示例代码)
-
java dom4j解析xml用到的几个方法
-
java使用xpath和dom4j解析xml
-
Android学习笔记之AndroidManifest.xml文件解析 博客分类: android androidAndroidManifest
-
Android学习笔记之AndroidManifest.xml文件解析(转) 博客分类: Android androidAndroidManifest
-
java dom4j解析xml文件代码实例分享
-
java使用dom4j操作xml示例代码