1.xml元素对应的对象实体类:
public class FileClass {
private String id;
private String name;
private String ids;
private String names;
private String prices;
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 getIds() {
return ids;
}
public void setIds(String ids) {
this.ids = ids;
}
public String getNames() {
return names;
}
public void setNames(String names) {
this.names = names;
}
public String getPrices() {
return prices;
}
public void setPrices(String prices) {
this.prices = prices;
}
@Override
public String toString() {
return "FileClass: id=" + id + ", ids=" + ids + ", name=" + name
+ ", names=" + names + ", prices=" + prices ;
}
}
2.对其进行封装的方法
public static void main(String[] args) throws Exception {
//目标: contact.xml信息 -> List集合
//1)读取xml文件
SAXReader reader = new SAXReader();
Document doc = reader.read(new File("./src/File.xml"));
//2)创建List对象
List<FileClass> list = new ArrayList<FileClass>();
//3)把xml信息->list对象
//3.1 读取到所有file标签
List<Element> fileList = doc.getRootElement().elements("file");
for (Element elem : fileList) {
//3.2 创建FileClass对象
FileClass f = new FileClass();
//3.3 把contact标签数据放入contact对象中
f.setId(elem.attributeValue("id"));
f.setName(elem.attributeValue("name"));
f.setIds(elem.elementText("ids"));
f.setNames(elem.elementText("names"));
f.setPrices(elem.elementText("prices"));
//3.4 把contact对象放入list对象
//保存数据 list.add(对象)
list.add(f);
}
//4)输出
for (FileClass file : list) {
System.out.println(file);
}
}