随便找一个简单的xml文件,存放进自己的项目中
data.xml
<?xml version="1.0" encoding="UTF-8"?>
<monitorCenter id="0" name="根">
<area id="108405" name="1" >
<concentrator id="108409" name="11" >
<nodeContrl id="108429" uid="111111111112" name="111" ></nodeContrl>
<nodeContrl id="108425" uid="111111111111" name="112" ></nodeContrl>
<groupMaintain id="108421" groupId="2" name="113"></groupMaintain>
<groupMaintain id="108417" groupId="1" name="114" >
<nodeContrl id="108433" uid="222222222222" name="1141" ></nodeContrl>
<groupMaintain id="108437" groupId="3" name="1142" >
<nodeContrl id="108445" uid="333333333333" name="11421" ></nodeContrl>
<groupMaintain id="108441" groupId="4" name="11422" ></groupMaintain>
</groupMaintain>
</groupMaintain>
</concentrator>
<concentrator id="108413" name="12" ></concentrator>
</area>
<area id="108449" name="2" ></area>
</monitorCenter>
java简单遍历
package com.royal.client;
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;
public class Dom4jClient {
private static String filePath = "src/main/java/com/royal/asset/data.xml";
public static void main(String args[]) {
SAXReader reader = new SAXReader();
try {
//读取xml文档
Document document = reader.read(filePath);
//得到xml文档根节点元素
Element root = document.getRootElement();
//获取根节点的子节点
// List<Element> elementList = root.elements();
// //得到子节点之后就是自由发挥的时候了,比如遍历子节点得到子节点的结点名称和节点的值
// Iterator<Element> it = elementList.iterator();
// Element element = null;
// while(it.hasNext()){
// element = it.next();
// System.out.println(element.attributeValue("name"));
// childElements(element);
// }
childElements(root,1);
} catch (DocumentException e) {
e.printStackTrace();
}
}
public static void childElements(Element element, int level){
String preStr = "";
for(int i = 1; i <= level; i++){
preStr += "------";
}
List<Element> elementList = element.elements();
Iterator<Element> it = elementList.iterator();
Element e = null;
while(it.hasNext()){
e = it.next();
System.out.println(level + preStr + e.attributeValue("name"));
childElements(e,level + 1);
}
}
}
别忘了导入dom4j jar包.
遍历结果: