package com.fenuang.sec;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.print.Doc;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.fenuang.demo4j.contest;
public class trueuse {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
// 实例化一个类用于添加xml文件
List<contest> list = new ArrayList<>();
SAXReader reader = new SAXReader();
Document doc = reader.read(new File("./conf/test.xml"));
// 读取指定标签
Iterator<Element> eleit = doc.getRootElement().elementIterator("user");
ArrayList newlist = new ArrayList(); // 创建新集合
while (eleit.hasNext()) {
Element ele = eleit.next();
contest con = new contest();
con.setId(ele.attributeValue("id"));
con.setName(ele.elementText("name"));
con.setEmail(ele.elementText("email"));
con.setQq(ele.elementText("qq"));
con.setWife(ele.elementText("wife"));
list.add(con);
Iterator it = list.iterator(); // 通过老集合获取迭代器
while (it.hasNext()) { // 遍历老集合
Object obj = it.next(); // 得到老集合的元素
if (!newlist.contains(obj)) {
newlist.add(obj);
}
}
}
System.out.println(list.get(0));
// System.out.println(" =======");
System.out.println(list.get(1));
// System.out.println(" =======");
System.out.println(list.get(2));
} catch (
Exception e) {
e.printStackTrace();
}
}
}
下面是用于存储元素的类
package com.fenuang.demo4j;
import org.omg.Messaging.SyncScopeHelper;
public class contest {
private String id;
private String name;
private String email;
private String qq;
private String wife;
/**
* @param id
* @param name
* @param email
* @param qq
* @param wife
*/
public contest(String id, String name, String email, String qq, String wife) {
super();
this.id = id;
this.name = name;
this.email = email;
this.qq = qq;
this.wife = wife;
}
/**
* @param id
* @param name
* @param email
* @param qq
* @param wife
*/
public contest() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getWife() {
return wife;
}
public void setWife(String wife) {
this.wife = wife;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.email + "--" + this.id + "--" + this.name + "--" + this.qq + "--" + this.wife+" ";
}
}
下面是要被读取的xml文件
<?xml version="1.0" encoding="utf-8"?>
<contestList>
<user id="001">
<name>王五</name>
<email>2222222</email>
<qq>4fenuang</qq>
<wife>6fenuang</wife>
</user>
<user id="002">
<name>李四</name>
<email>4444444</email>
<qq>4fenuang</qq>
<wife>6fenuang</wife>
</user>
<user id="003">
<name>张三</name>
<email>2fenuang</email>
<qq>333333</qq>
<wife>6fenuang</wife>
</user>
</contestList>