玄鉴
2016-07-25 17:36
谁有作业的答案?就是视频最后保存到集合中。还有一个问题属性值的时候需要for循环,怎么到了节点的时候没有for循环了呢?
package com.test; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class DOM4JTest { private static List<Book> books = new ArrayList<Book>(); public static void main(String[] args) { // 解析books.xml SAXReader reader = new SAXReader(); try { Document document = reader.read(new File("src/res/books.xml")); Element bookStore = document.getRootElement(); Iterator it = bookStore.elementIterator(); while(it.hasNext()){ Book bookEntity = new Book(); Element book = (Element)it.next(); List<Attribute> bookAttrs = book.attributes(); for (Attribute attr : bookAttrs) { System.out.println(attr.getName()+"->"+attr.getValue()); if(attr.getName().equals("id")){ bookEntity.setId(attr.getValue()); } } Iterator itt = book.elementIterator(); while(itt.hasNext()){ Element bookChild = (Element)itt.next(); System.out.println(bookChild.getName()+"->"+bookChild.getStringValue()); switch (bookChild.getName()) { case "name": bookEntity.setName(bookChild.getStringValue()); break; case "author": bookEntity.setAuthor(bookChild.getStringValue()); break; case "year": bookEntity.setYear(bookChild.getStringValue()); break; case "price": bookEntity.setPrice(bookChild.getStringValue()); break; case "language": bookEntity.setLanguage(bookChild.getStringValue()); break; default: break; } } books.add(bookEntity); bookEntity=null; System.out.println("--------------------------------"); } for (Book book : books) { System.out.println(book.toString()); System.out.println("--------------------------------"); } } catch (DocumentException e) { e.printStackTrace(); } } }
package com.test; public class Book { private String id; private String name; private String author; private String year; private String price; private String language; @Override public String toString() { return ("id->"+id+"\nname->"+name+"\nauthor->"+author+"\nyear->"+year+"\nprice->"+price+"\nlanguage->"+language); } public String getId() { return id; } public void setId(String id) { this.id = id; } 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 String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } }
for循环是为了遍历,每个book节点下的属性值和属性名。而下面是用了while循环遍历book下的节点名,和节点值。其实性质是一样的。而且在上一个循环也有用到一个while循坏来遍历book的个数的,但还需要遍历book里面的属性名和值,所以需要都一层循环而已。
Java眼中的XML---文件读取
83202 学习 · 431 问题
相似问题