1、xml文档
<?xml version="1.0" encoding="UTF-8"?>
<class>
<stu id="001">
<name>杨过</name>
<sex>男</sex>
<age>20</age>
</stu>
<stu id="002">
<name>小龙女</name>
<sex>女</sex>
<age>21</age>
<game name="英雄联盟">
<hero>炼金术士</hero>
<hero>虚空之女</hero>
</game>
</stu>
</class>
2、代码实现
在使用深度优先搜索遍历xml时得到的文档内容的顺序是逆序的,因为深度优先搜索使用的是栈的数据结构,由于先进后出所以得到的内容是逆序的
package com.excel.dom4j;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.*;
public class dom4jDemo {
/**
* 获取Document对象
* @param inputStream
* @return
*/
public static Document getDocument(InputStream inputStream) {
Document document = null;
try {
SAXReader saxReader = new SAXReader();
document = saxReader.read(inputStream); // 读取XML文件,获得document对象
} catch (Exception ex) {
ex.printStackTrace();
}
return document;
}
/**
* 获取根节点
* @param document
* @return
*/
public static Element getRoot(Document document) {
return document.getRootElement();
}
/**
* 深度优先搜索遍历xml
* @param root
*/
public static void DFS(Element root){
Stack<Element> elements = new Stack<>();
elements.push(root);
while (!elements.isEmpty()){
Element current = elements.pop();
Iterator<Node> iterator = current.nodeIterator();
while (iterator.hasNext()){
Node next = iterator.next();
if (next instanceof Element){
elements.push((Element) next);
System.out.println(next.getName()+" "+next.getText());
}
}
}
}
/**
* 广度有限搜索便利xml
* @param root
*/
public static void BFS(Element root){
Queue<Element> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()){
Element poll = queue.poll();
Iterator<Node> iterator = poll.nodeIterator();
while (iterator.hasNext()){
Node next = iterator.next();
if (next instanceof Element){
queue.offer((Element) next);
System.out.println(next.getName()+" "+next.getText());
}
}
}
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("xml/stu.xml");) {
Document document = getDocument(in);
Element root = getRoot(document);
BFS(root);
} catch (Exception e) {
e.printStackTrace();
}
}
}