最后的get为什么两本书就是0.。。还有我的输出为什么是 1 1 null 和 2 1 null
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; } }
package com.test; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; public class JDOMTest { private static List<Book> books = new ArrayList<Book>(); public static void main(String[] args) { SAXBuilder saxBuilder = new SAXBuilder(); try { Document document = saxBuilder.build(new FileInputStream("src/res/books.xml")); //根节点 Element rootElement = document.getRootElement(); //子节点 List<Element> bookList = rootElement.getChildren(); for (Element element : bookList) { Book book =new Book(); System.out.println("开始解析第" + (bookList.indexOf(element)+1)+"本书"); List<Attribute> attrList = element.getAttributes(); for (Attribute attr : attrList) { System.out.println(attr.getName()+"->"+attr.getValue()); if(attr.getName().equals("id")){ book.setId(attr.getValue()); } } List<Element> bookChilds = element.getChildren(); for (Element child : bookChilds) { System.out.println(child.getName()+"->"+child.getValue()); switch (child.getName()) { case "name": book.setName(child.getValue()); break; case "author": book.setAuthor(child.getValue()); break; case "year": book.setYear(child.getValue()); break; case "price": book.setPrice(child.getValue()); break; case "language": book.setLanguage(child.getValue()); break; default: break; } } books.add(book); book=null; System.out.println("--------------------------------------"); } for (Book book : books) { System.out.println(book.toString()); System.out.println("--------------------------------------"); } System.out.println(); } catch (JDOMException | IOException e) { e.printStackTrace(); } } }
我也有时就是跟着老师一步敲代码,但确实会出现错误,所以我建议你把代码复制上来,才可以真正的找到解决问题的方法!
我试过了,老师的代码没有问题,你可以到资料下载的位置把源代码下载下来,认真比对一下,看看是什么地方出了问题。
代码呢?