JDOM
解析实力:
public class JDOMParser {
private static ArrayList<Book> booksList = new ArrayList<Book>();
public static void main(String[] args) {
Book bookEn=null;
//进行对books.xml文件的JDOM解析
//1.创建一个SAXBulider对象
SAXBuilder saxBuilder = new SAXBuilder();
InputStream in ;
try {
//2.创建一个输入流,将xml文件加载到输入流中
in = new FileInputStream("books.xml");
//3.通过saxBuilder对象的build方法,将输入流加载到saxBuilder对象中
Document document = saxBuilder.build(in);
//4.通过document对象获取xml文件的根节点
Element rootElement = document.getRootElement();
//5.获取根节点下的子节点的集合
List<Element> bookList = rootElement.getChildren();
for (Element book : bookList) {
System.out.println("开始解析第"+(bookList.indexOf(book)+1)+ "本书");
//解析book属性
List<Attribute> attrList = book.getAttributes();
for (Attribute attr : attrList) {
bookEn = new Book();
//获取属性名,属性值
String name = attr.getName();
String value = attr.getValue();
System.out.println("属性名:"+name +"--属性值:"+value);
if(attr.getName().equals("id")){
bookEn.setId(value);
}
}
List<Element> childList = book.getChildren();
for (Element child : childList) {
System.out.println("节点名:"+child.getName()+"--节点值:"+child.getValue());
if(child.getName().equals("name")){
bookEn.setName(child.getValue());
}else if(child.getName().equals("author")){
bookEn.setAuthor(child.getValue());
}else if(child.getName().equals("year")){
bookEn.setYear(child.getValue());
}else if(child.getName().equals("price")){
bookEn.setPrice(child.getValue());
}else if(child.getName().equals("language")){
bookEn.setLanguage(child.getValue());
}
}
System.out.println(bookEn);
System.out.println("结束解析第"+(bookList.indexOf(book)+1+ "本书");
booksList.add(bookEn);
bookEn = null;
System.out.println(booksList.size());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}