使用jdom方法解析传入的xml文件
public class xmlTest {
public static void main(String[] args) {
// 输入存储指定数据的集合的class对象使用反射返回解析数据
// 方法名parse
// 参数存储数据的class对象,xml文件对象
// 返回值返回存储数据的类型的集合
ArrayList<txt>parse= xmlTest.parse(new File("D:/test/Txt.xml"), txt.class);
System.out.println(parse);//输出到控制台显示
}
public static<E> ArrayList<E> parse(File f,Class<E> c){
//创建存储指定泛型数据集合 存储返回解析xml数据的集合
ArrayList<E> list=new ArrayList<>();
try {
//创建sax解析器 解析制定xml文件(jdom本身没有解析器,本质还是使用sax解析器读取)
SAXBuilder saxBuilder=new SAXBuilder();
//获取包含xml文件数据的dom对象
Document dom = saxBuilder.build(f);
//获取根源上对象
Element rootElement = dom.getRootElement();
//获取根元素子元素集合 jdom不能直接获取子元素的子元素
List<Element> children = rootElement.getChildren();
//遍历获取每个子元素对象(每个存储数据的对象)
for (Element element : children) {
//使用class对象调用无参构造方法创建对象
E newInstance = c.newInstance();
//继续获取子元素对象集合
List<Element> children2 = element.getChildren();
//遍历子元素中的所有元素
for (Element element2 : children2) {
//根据元素名字使用反射获取指定类对应属性对象
Field declaredField = c.getDeclaredField(element2.getName());
//赋权,私有属性使用前必须赋权
declaredField.setAccessible(true);
//使用属性对象为指定属性赋值
declaredField.set(newInstance, element2.getValue());
}
//将循环结束后存储数据的对象存入集合
list.add(newInstance);
}
}
catch (NoSuchFieldException e) {
System.err.println("xml文件属性与存储数据类型不匹配");
}
catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
例,储指定数据的集合的class类
public class txt implements Serializable{
private String name;
private String author;
private String year;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public txt(String name, String author, String year) {
super();
this.name = name;
this.author = author;
this.year = year;
}
public txt() {
super();
}
@Override
public String toString() {
return "txt [name=" + name + ", author=" + author + ", year=" + year + "]";
}
}
用于解析的xml文件
<?xml version="1.0" encoding="UTF-8"?>
<txts>
<txt>
<name>西游记</name>
<author>吴承恩</author>
<year>1666</year>
</txt>
<txt>
<name>三国演义</name>
<author>罗贯中</author>
<year>1333</year>
</txt>
</txts>
运行结果:
[txt [name=西游记, author=吴承恩, year=1666], txt [name=三国演义, author=罗贯中, year=1333]]