递归解析XML

时间:2023-03-08 16:46:32

  递归解析XML

 package com.app.test;

 import java.io.InputStream;
import java.util.List; import org.dom4j.Attribute;
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时Juint的常用注解,选择函数名字 右键Run as Junit Test @Test
public void testParseXML() throws DocumentException {
SAXReader reader = new SAXReader();
InputStream is = this.getClass().getClassLoader()
.getResourceAsStream("weather.xml");
Document doc = reader.read(is);
Element root = doc.getRootElement();
printChild(root);
} public void printChild(Element root) {
@SuppressWarnings("unchecked")
List<Element> childList = root.elements();
System.out.println(root.getName()+" "+root.getText());
for (Element e : childList) {
if (e.elements().size() == 0) {
@SuppressWarnings("unchecked")
List<Attribute> attributeList = e.attributes();
for (Attribute a : attributeList) {
System.out.println(a.getName() + ":" + a.getValue());
}
System.out.println(e.getName() + " " + e.getText());
} else {
System.out.println(e.getName());
List<Attribute> attributeList = e.attributes();
for (Attribute a : attributeList) {
System.out.println(a.getName() + ":" + a.getValue()+"======================");
}
printChild(e);
}
}
}
}