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();
}
}
}