差三岁4185231
2016-12-18 01:34
如果我只知道有books.xml文件 我怎么知道下面有bookstore这个节点 然后又怎么得到下面的两个book节点呢 不知道的情况下
package com.javatoxml.dom4jtest; 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; import com.javatoxml.entiry.Book; public class DOM4JTest { // private static Book bookEntiry ; private static ArrayList<Book> booksList = new ArrayList<Book>(); public static void main(String[] args) { //创建SAXReader对象 SAXReader reader = new SAXReader(); //通过reader方法加载books.xml文件 try { Document document = reader.read(new File("src/res/books.xml")); //通过document对象获取根节点bookStore Element bookStore = document.getRootElement(); //通过element对象的elementIterator方法获取迭代器 Iterator it = bookStore.elementIterator(); //历遍迭代器,获取根节点中的信息 while (it.hasNext()) { Book bookEntiry = new Book(); Element book = (Element)it.next(); //获取book的属性名以及属性值 List<Attribute> bookAttrs = book.attributes(); for (Attribute attr : bookAttrs) { System.out.println("属性名:" + attr.getName() + "---属性值:" + attr.getValue()); bookEntiry.setId(attr.getValue()); } Iterator itt = book.elementIterator(); while (itt.hasNext()) { Element bookChild = (Element) itt.next(); System.out.println("节点名:" + bookChild.getName() + "---节点值:" + bookChild.getStringValue()); if (bookChild.getName().equals("name")) { bookEntiry.setName(bookChild.getStringValue()); } else if (bookChild.getName().equals("author")){ bookEntiry.setAuthor(bookChild.getStringValue()); } else if (bookChild.getName().equals("year")) { bookEntiry.setYear(bookChild.getStringValue()); } else if (bookChild.getName().equals("price")) { bookEntiry.setPrice(bookChild.getStringValue()); } else if (bookChild.getName().equals("language")) { bookEntiry.setLanguage(bookChild.getStringValue()); } } booksList.add(bookEntiry); System.out.println(booksList.size()); bookEntiry = null; } for (Book books : booksList) { System.out.println(books.getId()); System.out.println(books.getName()); System.out.println(books.getAuthor()); System.out.println(books.getYear()); System.out.println(books.getPrice()); System.out.println(books.getLanguage()); System.out.println("------finishi-----"); } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //在接下来学习DOM4J解析中你能找到答案,代码注释已经写的很清楚了
Java眼中的XML---文件读取
83199 学习 · 431 问题
相似问题