- import java.io.File;
- import java.util.Iterator;
- import java.util.List;
- import org.dom4j.Document;
- import org.dom4j.DocumentException;
- import org.dom4j.Element;
- import org.dom4j.io.SAXReader;
- import org.junit.Test;
- public class Dom4jTest {
- @Test
- public void test() throws DocumentException {
- // 创建文件对象
- File file = new File("src/dom4j/sida.xml");
- // 得到document对象
- Document document = parse(file);
- // 获取文档根节点
- Element root = document.getRootElement();
- // System.out.println("根节点名:"+root.getName());
- // nodeChild(root);
- listNode(root);
- }
- public Document parse(File file) throws DocumentException {
- // 读取XML文件,获得document对象
- SAXReader reader = new SAXReader();
- Document document = reader.read(file);
- return document;
- }
- public void nodeChild(Element element) {
- // 得到指定ID的元素节点对象
- Element el = element.elementByID("x001");
- System.out.println(el);
- // 得到指定标签名的元素节点对象
- Element elem = element.element("西游记");
- System.out.println(elem.getName());
- // 得到指定元素名的元素集合
- List<Element> list = elem.elements("作者");
- for (Element e : list) {
- System.out.println(e.getName());
- }
- System.out.println();
- }
- public void listNode(Element element) {
- // 得到子元素对象迭代器
- Iterator<Element> it = element.elementIterator();//子节点的集合的迭代器
- // 判断是否含有下一个元素
- while (it.hasNext()) {
- // 得到迭代其中的每一个元素
- Element el = it.next();
- // 输出
- System.out.println(el.getName());
- // 迭代处理
- listNode(el);
- }
- }
- }
XML文件
- <!DOCTYPE 四大名著[
- <!ELEMENT 四大名著 (西游记,红楼梦)>
- <!ATTLIST 西游记 id ID #IMPLIED>
- ]>
- <四大名著>
- <西游记 id="x001">
- <作者>
- <姓名>吴承恩</姓名>
- <性别>男</性别>
- </作者>
- </西游记>
- <红楼梦 id="x002">
- <作者>曹雪芹</作者>
- </红楼梦>
- </四大名著>