【慕课笔记】4-5 应用DOM4J及JDOM方式解析XML—在JDOM中存储Book对象

来源:互联网 发布:网络怎么赚钱 编辑:程序博客网 时间:2024/04/19 19:56
package com.imooc.xml;  import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;import java.util.List;import org.jdom.Attribute;import org.jdom.Document;import org.jdom.Element;import org.jdom.JDOMException;import org.jdom.input.SAXBuilder;public class TestJDOM {private static ArrayList<Book> bookslist=new ArrayList<Book>();public static void main(String[] args) {//进行对book.xml文件的JDOM解析//准备工作//1.创建一个SAXBuilder对象SAXBuilder saxBuilder=new SAXBuilder();//2.创建一个输入流,将xml文件加载到输入流中InputStream in;try {in = new FileInputStream("src/res/haha.xml");//3.通过saxBuilder的build方法,将输入流加载到saxBuilder中Document document=saxBuilder.build(in);//4.通过document对象获取xml文件的根节点Element rootelement=document.getRootElement();//5.获取根节点下的子节点的List集合List<Element> booklist=rootelement.getChildren();//继续进行解析for(Element book:booklist){Book bookentity=new Book();System.out.println("-----开始解析第"+(booklist.indexOf(book)+1)+"本书-----");//解析book的属性集合List<Attribute> attrlist=book.getAttributes();//知道节点下属性名称是,获取节点值//book.getAttributeValue("id");//遍历attrlist(针对不清楚book节点下属性的名字和数量)for(Attribute attr:attrlist){//获取属性名String attrname=attr.getName();//获取属性值String attrvalue=attr.getValue();System.out.println("属性名:"+attrname+"  属性值:"+attrvalue);if(attrname.equals("id")){bookentity.setId(attrvalue);}}//对book节点的子节点的节点名及节点值的遍历List<Element> bookchilds=book.getChildren();for(Element child:bookchilds){System.out.println("节点名:"+child.getName()+"  结点值:"+child.getValue());if(child.getName().equals("name")){bookentity.setName(child.getValue());}else if(child.getName().equals("author")){bookentity.setAuthor(child.getValue());}else if(child.getName().equals("price")){bookentity.setPrice(child.getValue());}else if(child.getName().equals("year")){bookentity.setYear(child.getValue());}else if(child.getName().equals("language")){bookentity.setLanguage(child.getValue());}}System.out.println("-----结束解析第"+(booklist.indexOf(book)+1)+"本书-----");bookslist.add(bookentity);bookentity=null;System.out.println(bookslist.size());}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (JDOMException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

0 0