Java 使用 dom4j 读取 xml文档 demo

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns="http://www.example.org/web-app_2_5" 
 3             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4             xsi:schemaLocation="http://www.example.org/web-app_2_5 web-app_2_5.xsd"
 5             version="2.5">
 6             
 7     <servlet>
 8         <servlet-name>hello</servlet-name>
 9         <servlet-class>doclwe4</servlet-class>
10     </servlet>        
11     <servlet-mapping>
12         <servlet-name>hello</servlet-name>
13         <url-pattern>/hello</url-pattern>
14     </servlet-mapping>    
15             
16 </web-app> 
 1 package xmldemo;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileNotFoundException;
 5 import java.io.InputStream;
 6 import java.util.List;
 7 
 8 import javax.xml.stream.events.StartDocument;
 9 
10 import org.dom4j.Document;
11 import org.dom4j.DocumentException;
12 import org.dom4j.Element;
13 import org.dom4j.io.SAXReader;
14 
15 
16 public class dom4jDemo {
17 
18     public static void main(String[] args) {
19         // TODO Auto-generated method stub
20         try {
21             testSaxReader();
22         } catch (Exception e) {
23             // TODO: handle exception
24             e.printStackTrace();
25         }
26         
27     }
28     
29     
30     public static void testSaxReader() throws DocumentException, FileNotFoundException {
31         SAXReader saxReader = new SAXReader();
32         FileInputStream file = new FileInputStream("src/xmldemo/schemademo.xml");
33         Document doc = saxReader.read(file);
34         Element root = doc.getRootElement(); //获取根元素
35         System.out.println(root.getName());//获取根元素的名称
36         System.out.println(root.attributeValue("version")); //获取根元素上 version 属性
37         List<Element> childsElement = root.elements();
38         for(Element child : childsElement) {
39              if ("servlet".equals(child.getName())) {
40                 //拿到 所有标签是servlet 的 标签
41                  Element servlet_name = child.element("servlet-name"); //拿到 servlet-name 标签
42                  Element servlet_class = child.element("servlet-class"); //拿到 servlet-class 标签
43                  System.out.println(servlet_name.getData());
44                  System.out.println(servlet_class.getData());
45             }
46         }
47         
48     }
49 }

 

posted @ 2017-12-21 17:57  ZhenJie.W  阅读(739)  评论(0编辑  收藏  举报