既然前面说了DOM4J这里好那里好,大家都是在用这个,那咱就不得不写一个了。
XML文件:
<?xml version="1.0" encoding="UTF-8" ?>
<person>
<from where="Others">
<name>Jack</name>
<age>25</age>
<sex>boy</sex>
<hobby>sing songs</hobby>
</from>
<from where="China">
<name>桔子桑</name>
<age>26</age>
<sex>男</sex>
<hobby>看书、画画</hobby>
</from>
</person>
Person类,用于存储解析所得信息:
package com.dom.node; public class Person {
String where;
String name;
String age;
String sex;
String hobby;
public void setWhere(String where) {
this.where = where;
}
public void setName(String name) {
this.name = name;
}
public void setAge(String age) {
this.age = age;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
@Override
public String toString() {
return "Person [where=" + where + ", name=" + name + ", age=" + age + ", sex=" + sex + ", hobby=" + hobby + "]";
}
}
DOM4J解析方法类:
package com.dom.node; import java.util.*;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader; public class Dom4jxml {
public static void main(String[] args) {
try {
SAXReader reader = new SAXReader();
Document document = reader.read("file/clear.xml");
Element rootElement = document.getRootElement();
Iterator<Element> it =rootElement.elementIterator();
List<Person> personlist = new ArrayList<Person>();
while(it.hasNext()) {
Person person = new Person();
Element son1=(Element)it.next();
List<Attribute> attrlist1 =son1.attributes();
for (Attribute attr : attrlist1) {
if(attr.getName().equals("where")) {
person.setWhere(attr.getValue());
}
}
Iterator itt = son1.elementIterator();
while(itt.hasNext()) {
Element son2 =(Element)itt.next();
if(son2.getName().equals("name")) {
person.setName(son2.getStringValue());
}else if(son2.getName().equals("age")) {
person.setAge(son2.getStringValue());
}else if(son2.getName().equals("sex")) {
person.setSex(son2.getStringValue());
}else if(son2.getName().equals("hobby")) {
person.setHobby(son2.getStringValue());
}
}
personlist.add(person);
person=null;
}
System.out.println("总人数:"+personlist.size()+"人");
for (Person person : personlist) {
System.out.println(person.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
控制台打印输出:
总人数:2人
Person [where=Others, name=Jack, age=25, sex=boy, hobby=sing songs]
Person [where=China, name=桔子桑, age=26, sex=男, hobby=看书、画画]
总结一下其中获取节点相关数据的方法吧,以免混淆;
SAXReader reader = new SAXReader(); //新建SAXReader对象
Document document = reader.read("file/clear.xml"); //read()方法将xml文件载入当前程序
Element rootElement = document.getRootElement(); //getRootElement()方法获取文档的根节点
Iterator<Element> it =rootElement.elementIterator(); //elementIterator()返回一个迭代器
attributes() ; //返回节点的属性(List集合)
getName(); //得到属性名或者节点名
getValue(); //得到属性值
getStringValue(); //得到节点内部的字符串