package com.imooc.jdomtest;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;import javax.imageio.stream.FileImageInputStream;import org.jdom2.Attribute;import org.jdom2.Document;import org.jdom2.Element;import org.jdom2.JDOMException;import org.jdom2.input.SAXBuilder;import com.imooc.entity.Book;public class JDOMTest { private ?static ArrayList<Book> booksList = new ArrayList<Book>(); public static void main(String[] args) { // 進行對books.xml文件的JDOM解析 // 準備工作 // 1、創(chuàng)建一個SAXBuilder的對象 SAXBuilder saxBuilder = new SAXBuilder(); InputStream in; try { // 2、創(chuàng)建一個輸入流,將xml文件加載到輸入流中 in = new FileInputStream("src/res/books.xml"); //解決中文亂碼問題// InputStreamReader isr = new InputStreamReader(in, "UTF-8");// Document document = saxBuilder.build(isr); // 3、通過saxBuilder的build方法將輸入流加載到saxBuilder中 Document document = saxBuilder.build(in); // 4、通過document對象獲取xml文件的跟節(jié)點 Element rootElement = document.getRootElement(); // 5、獲取根節(jié)點下的子節(jié)點的List集合 List<Element> bookList = rootElement.getChildren(); // 繼續(xù)進行解析 for (Element book : bookList) { Book bookEntity = new Book();? System.out.println("======開始解析第" + (bookList.indexOf(book) + 1) + "本書======="); // 解析book的屬性集合 List<Attribute> attrList = book.getAttributes(); // //針知道節(jié)點下屬性名稱時,獲取節(jié)點值 // book.getAttributeValue("id"); // 遍歷attrList(針對不清楚book節(jié)點下屬性的名字及數(shù)量 ) for (Attribute attribute : attrList) { // 獲取屬性名 String attrName = attribute.getName(); // 獲取屬性值 String attrValue = attribute.getValue(); System.out.println("屬性名:" + attrName + "---屬性值:" + attrValue); if(attrName.equals("id")){ bookEntity.setId(attrValue); } } // 對book節(jié)點的子節(jié)點的節(jié)點名以及節(jié)點值的遍歷 List<Element> bookChilds = book.getChildren(); for (Element child : bookChilds) { System.out.println("節(jié)點名:" + child.getName() + "---節(jié)點值:"? + child.getValue()); if(child.equals("name")){ bookEntity.setName(child.getValue()); } else if(child.equals("author")){ bookEntity.setAuthor(child.getValue()); } else if(child.equals("year")){ bookEntity.setYear(child.getValue()); } else if(child.equals("price")){ bookEntity.setPrice(child.getValue()); } else if(child.equals("language")){ bookEntity.setLanguage(child.getValue()); } } System.out.println("======結(jié)束解析第" + (bookList.indexOf(book) + 1) + "本書======="); booksList.add(bookEntity); bookEntity = null; System.out.println(booksList.size()); System.out.println(booksList.get(0).getId()); System.out.println(booksList.get(0).getName()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}
添加回答
舉報
0/150
提交
取消