package com.imooc.learn3;



import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

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 {


public static void main(String[] args) throws JDOMException, IOException {

//对Books.xml进行解析

SAXBuilder saxBuilder=new SAXBuilder();

//创建一个输入流

FileInputStream in=new FileInputStream("demo/Books.xml");

//通过SaxBuilder来处理文件输入流

Document document=saxBuilder.build(in);

//通过document对象来获取xml的根节点

Element root=document.getRootElement();

//通过getChildren来获取根节点下面子节点的集合

List<Element> aList=root.getChildren();

//通过For循环来遍历

for (Element element : aList) {

System.out.println("====开始解析第"+(aList.indexOf(element)+1)+"本书====");

System.out.println(element.getName()+"----");

List<Attribute> attrList=element.getAttributes();

//遍历attrList,对于不知道节点的属性名和值

for (Attribute attribute : attrList) {

System.out.println("属性名是:"+attribute.getName());

System.out.println("该属性值是"+attribute.getValue());

}

//针对book的子节点的节点名和节点值进行遍历

List<Element> chiList=element.getChildren();

for (Element elechild : chiList) {

System.out.println("节点名字是:"+elechild.getName()+"节点值是:"+elechild.getValue());

//
System.out.println();

}

System.out.println("====结束解析第"+(aList.indexOf(element)+1)+"本书====");



}


}



}