jdom解析xml檔案

範水水今年暴富發表於2020-11-09

標題

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>

在這裡插入圖片描述

相關文章