JDOM解析xml文件
程序员文章站
2022-05-28 11:54:53
...
标题
JDOM解析xml文件
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
public class Jdom {
public static void main(String[] args) throws Exception {
ArrayList<Book> list=new ArrayList<>();
SAXBuilder sb=new SAXBuilder(); //创建sax解析器
Document dom = sb.build(new File("src/NewFile.xml")); //使用sax解析器加载指定xml文件 返回存储所有数据的dom对象
Element rootElement = dom.getRootElement(); // 获取根元素对象
List<Element> bookList = rootElement.getChildren(); // 获取指定元素对象所有子元素
for (Element book : bookList) {
Book b=new Book();
List<Element> fieldList = book.getChildren(); // 获取每个student元素的子元素(属性集合)
for (Element field : fieldList) {
if(field.getName().equals("name")){
b.setName(field.getValue());
}else if(field.getName().equals("author")){
b.setAuthor(field.getValue());
}else if(field.getName().equals("year")){
b.setYear(field.getValue());
}
}list.add(b);
}System.out.println(list);
}
}
import java.io.Serializable;
public class Book implements Serializable{
public String name;
public String author;
public String year;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuther() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public Book(String name, String auther, String year) {
super();
this.name = name;
this.author = auther;
this.year = year;
}
public Book() {
super();
}
@Override
public String toString() {
return "Book [name=" + name + ", author=" + author + ", year=" + year + "]";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<name>书名</name>
<author>作者</author>
<year>年份</year>
</book>
<book>
<name>金瓶梅</name>
<author>兰陵笑笑生</author>
<year>1900</year>
</book>
</books>
上一篇: Drools学习专栏三