递归解析XML

           

  递归解析XML

 1 package com.app.test;

 2 

 3 import java.io.InputStream;

 4 import java.util.List;

 5 

 6 import org.dom4j.Attribute;

 7 import org.dom4j.Document;

 8 import org.dom4j.DocumentException;

 9 import org.dom4j.Element;

10 import org.dom4j.io.SAXReader;

11 import org.junit.Test;

12 

13 public class Dom4jTest {

14     //test时Juint的常用注解,选择函数名字 右键Run as Junit Test

15 

16     @Test

17     public void testParseXML() throws DocumentException {

18         SAXReader reader = new SAXReader();

19         InputStream is = this.getClass().getClassLoader()

20                 .getResourceAsStream("weather.xml");

21         Document doc = reader.read(is);

22         Element root = doc.getRootElement();

23         printChild(root);

24     }

25 

26     public void printChild(Element root) {

27         @SuppressWarnings("unchecked")

28         List<Element> childList = root.elements();

29         System.out.println(root.getName()+" "+root.getText());

30         for (Element e : childList) {

31             if (e.elements().size() == 0) {

32                 @SuppressWarnings("unchecked")

33                 List<Attribute> attributeList = e.attributes();

34                 for (Attribute a : attributeList) {

35                     System.out.println(a.getName() + ":" + a.getValue());

36                 }

37                 System.out.println(e.getName() + " " + e.getText());

38             } else {

39                 System.out.println(e.getName());

40                 List<Attribute> attributeList = e.attributes();

41                 for (Attribute a : attributeList) {

42                     System.out.println(a.getName() + ":" + a.getValue()+"======================");

43                 }

44                 printChild(e);

45             }

46         }

47     }

48 }

 

你可能感兴趣的:(解析xml)