2016/04/27(XML)
package com.wode.test;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.dom.DOMNodeHelper.EmptyNodeList;
import org.dom4j.io.SAXReader;
/**
*
* @author Administrator
*读取XML 文件
*/
public class ReadXml {
public static void main(String[] args) {
SAXReader saxReader = new SAXReader();//获得解析器
File file = new File("src/com/wode/test/Book.xml");//获得文件
try {
Document document = saxReader.read(file);//构造文档树并且返回
Element rootElement = document.getRootElement();//获得 根元素
List<Element> list = rootElement.elements("book");//获得 book元素
Iterator<Element> it=list.iterator();//使用迭代器 迭代
Element element=null;
/*while(it.hasNext()){
element = it.next();
//获得 相应的 信息
System.out.println(element.elementText("name"));
System.out.println(element.elementText("author"));
System.out.println(element.elementText("price"));
}*/
//获得 属性
while(it.hasNext()){
element = it.next();
List lis= element.attributes();//用List 集合 储存数据
Iterator<Element> iterator=lis.iterator();//使用迭代器 迭代
while (iterator.hasNext()) {
Attribute attribute = (Attribute) iterator.next();
System.out.println(attribute.getName()+" "+attribute.getValue());
}
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<books >
<book id="12315">
<name>盗墓笔记</name>
<author>南派三叔</author>
<price>88.88</price>
</book>
<book id="12316">
<name>三国演义</name>
<author>罗贯中</author>
<price>87.88</price>
</book>
</book>
<book id="12317">
<name>西游记</name>
<author>吴承恩</author>
<price>88.8</price>
</book>
</book>
<book id="12318">
<name>水浒传</name>
<author>施耐庵</author>
<price>83.88</price>
</book>
</book>
<book id="12319">
<name>红楼梦</name>
<author>曹雪芹</author>
<price>81.88</price>
</book>
</books>