以JDOM方式解析
一、準備工作
1.導入jdom的jar包
2.SAXBuilder saxBuilder = new SAXBuilder(); //創建SAXBuilder對象
3.Document document = saxBuilder.build(in); //創建document對象 (導入的是org.jdom….下的包)。build()方法有重載。這裏採用傳入文件流的方式 InputStream in = new FileInputStream(“src/res/books.xml”);
二、解析XML
4.Element rootElement = document.getRootElement(); //獲取根節點
5.List bookList = rootElement.getChildren(); //獲取節點下的子節點集合
for (Element book : bookList) { //遍歷子節點
List attrList = book.getAttributes(); //獲取每個子節點的屬性集合
for (Attribute attribute : attrList) { //遍歷屬性集合
String attrName = attribute.getName(); //獲取屬性名
String attrValue = attribute.getValue(); //獲取屬性值
System.out.println(attrName + ” = ” + attrValue);
}
List childElementList = book.getChildren(); //同樣的方法獲取子節點的子節點
for (Element child : childElementList) { //遍歷
System.out.println(child.getName() + ” = ” + child.getValue());
}}
注意:JDOM解析XML時的亂碼問題
- 方法一:修改XML中<?xml version=”1.0” encoding=”UTF-8”?>” 的encoding屬性值,對中文支持較好的有UTF-8,GBK,gb2312 等
- 方法二:在創建文件輸入流時用InputStreamReader進一步包裝輸入文
件流
1.InputStream in = new FileInputStream(filePath);
2.InputStreamReader isr = InputStreamReader(InputStream in , charset charsetName); //將charsetName設爲對中文支持較好的有UTF-8,GBK,gb2312 等
3.Document document = saxBuilder.build(isr);