DOM 解析XML 是一次性读取,也就是把XML当作一个对象读取。
1.准备XML
<?xml version="1.0" encoding="utf-8" ?>
<peopel>
<person personid="m001">
<name>Tony</name>
<address>beijing</address>
<tel>10086</tel>
<fax>3122321</fax>
<mail>3124432@qq.com</mail>
</person>
<person personid="m002">
<name>Tom</name>
<address>suzhou</address>
<tel>1892312325</tel>
<fax>5343</fax>
<mail>444444@qq.com</mail>
</person>
</peopel>
2.根据XML 准备一个类
class Person{
private String personid;
private String name;
private String address;
private String tel;
private String fax;
private String mail;
public Person() {
}
@Override
public String toString() {
return "peopel{" +
"personid='" + personid + '\'' +
", name='" + name + '\'' +
", address='" + address + '\'' +
", tel='" + tel + '\'' +
", fax='" + fax + '\'' +
", mail='" + mail + '\'' +
'}';
}
public String getPersonid() {
return personid;
}
public void setPersonid(String personid) {
this.personid = personid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
}
3.实现代码
DocumentBuilderFactory doc= DocumentBuilderFactory.newInstance();//创建一个解析工厂
DocumentBuilder docb=doc.newDocumentBuilder();//生成解析器
InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("test.xml");//一次性读取全部文件内容
Document docc= docb.parse(in);//加载到内存
List<Person> lp=new ArrayList<>();
NodeList pnodelist=docc.getElementsByTagName("person"); //把标签 person 一次读取到
//循环解析这个Person 因为有多层所以这个是第一层
for(int i=0;i<pnodelist.getLength();i++){
Node pn= pnodelist.item(i);
Person p=new Person();
//-----------------------先存储第一层
p.setPersonid(pn.getAttributes().getNamedItem("personid").getNodeValue());
NodeList nl= pn.getChildNodes();
for (int j=0;j<nl.getLength();j++){
//遍历第一层内部成员
Node nd= nl.item(j);
String tbg= nd.getNodeName();
//System.out.println(tbg);
if ("name".equals(tbg)){
p.setName(nd.getFirstChild().getNodeValue());
}else
if ("mail".equals(tbg)){
p.setMail(nd.getFirstChild().getNodeValue());
}else
if ("fax".equals(tbg)){
p.setFax(nd.getFirstChild().getNodeValue());
}else
if ("tel".equals(tbg)){
p.setTel(nd.getFirstChild().getNodeValue());
}else
if ("address".equals(tbg)){
p.setAddress(nd.getFirstChild().getNodeValue());
};
}
//结束后存存储到集合中
lp.add(p);
}
//查看运行效果
lp.forEach((tt)-> System.out.println(tt.toString()));
效果
peopel{personid=‘m001’, name=‘Tony’, address=‘beijing’, tel=‘10086’, fax=‘3122321’, mail=‘3124432@qq.com’}
peopel{personid=‘m002’, name=‘Tom’, address=‘suzhou’, tel=‘1892312325’, fax=‘5343’, mail=‘444444@qq.com’}