public class main {
private static ArrayList<Book> booksList = new ArrayList<Book>();
public static void main(String[] args) {
SAXBuilder saxBuilder = new SAXBuilder();
InputStream in;
try {
in = new FileInputStream("books.xml");
InputStreamReader isr = new InputStreamReader(in, "utf-8");
Document document = saxBuilder.build(isr);
// 获取根节点
Element rootElement = document.getRootElement();
// 获取根节点下的子节点
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) {
/**
* element getvalue Returns the XPath 1.0 string value of this element, which is the complete, ordered content of * all text node descendants of this element
*/
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("year")) {
bookEntity.setYear(child.getValue());
}
else if (child.getName().equals("price")) {
bookEntity.setPrice(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());
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();
}
}
}