dom4j 解析xml文档

<?xml version="1.0" encoding="UTF-8"?>  
<students>  
    <student>  
        <name sn="01">张三</name>  
        <age>18</age>  
    </student>  
    <student>  
        <name sn="02">李四</name>  
        <age>20</age>  
    </student>  
</students>  

import java.io.File;   
import org.dom4j.DocumentException;   
import org.dom4j.Element;   
import org.dom4j.ElementHandler;   
import org.dom4j.ElementPath;   
import org.dom4j.io.SAXReader;   
/**  
 * 在不读完XML文档的时候解析里面的数据  
 * ElemnetHandler  
 * ElementPath  
 * @author Administrator  
 *  
 */  
  
public class ElementHandlerTest {   
    public static void main(String[] args){   
        //创建一个SAXReader对象来读取XML文档   
        SAXReader sax = new SAXReader();   
        //ADD一个Handler,用于监听,当读到对应元素时,采取相应的onStart,onEnd里面编写的方法   
        //还要指定路径,有相对的,也有绝对的,下面就是绝对的   
        //StudentHandler()和NameHandler()都是绝内部类,都implement ElementHandler   
        sax.addHandler("/students/student", new ElementHandlerTest.StudentHandler());   
        try {   
            //读取一个XML文档,返回一个Document对象   
            //读的时候就监听   
            sax.read(new File("students.xml"));   
               
        } catch (DocumentException e) {   
            e.printStackTrace();   
        }   
    }   
    private static class StudentHandler implements ElementHandler{   
        public void onStart(ElementPath elementPath) {   
            //getCurrent()获得当前元素   
            Element e = elementPath.getCurrent();   
            //attributeValue("sn"))获得当前元素的sn属性   
            System.out.println(e.attributeValue("sn"));   
            //ElementPath里面也可以添加addHandler,这里面用的是相对路径   
            elementPath.addHandler("name", new ElementHandlerTest.NameHandler());   
        }   
  
        public void onEnd(ElementPath elementPath) {   
            elementPath.removeHandler("name");   
        }   
    }   
       
    private static class NameHandler implements ElementHandler{   
        public void onStart(ElementPath elementPath) {   
            //获得当前路径   
            System.out.println(elementPath.getPath());   
        }   
        public void onEnd(ElementPath elementPath) {   
               
            Element e = elementPath.getCurrent();   
            //获得元素的值和名字   
            System.out.println(e.getName()+":"+e.getText());   
        }   
           
    }   
}  

你可能感兴趣的:(dom4j)