package com.imooc.jdomtest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//进行对books.xml文件的JDOM解析
//准备工作
//1.创建一个SAXBuilder对象
SAXBuilder saxBuilder = new SAXBuilder();
InputStream in;
try {
//2.创建一个输入流,将XML文件加载到输入流中来
in = new FileInputStream("src/res/books.xml");
InputStreamReader isr =new InputStreamReader(in, "UTF-8");
//3.通过saxBuilder的build方法,将输入流加载到saxBuilder中
Document document= saxBuilder.build(isr);
//4.通过document对象获取xml文件的根节点
Element rootelement = document.getRootElement();
//5.获取根节点下的子节点的List集合
List<Element> bookList = rootelement.getChildren();
//继续进行解析
for (Element book : bookList) {
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);
}
//对book节点的子节点的节点名以及节点值的遍历
List<Element> bookChilds = book.getChildren();
for (Element child : bookChilds) {
System.out.println("节点名:" + child.getName() + "------节点值:"
+ child.getValue());
}
System.out.println("=======结束解析第"
+ (bookList.indexOf(book) + 1) + "书=======");
}
}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();
}
}
}
InputStreamReader isr =new InputStreamReader(in, "UTF-8");--->InputStreamReader isr =new InputStreamReader(in, "gbk"); 就可以了
因为项目的Resource---->Text file encodeing---->Inherited from container (GBK)