import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.junit.Test;

/**
 * 解析xml
 * @author WangShuang
 *
 */
public class Demo {
    /**
     * 获取xml标签的文本内容和属性值
     * @param args
     */
    @Test
    public void run1() {
        try {
            //1.创建解析器对象
            SAXReader sax = new SAXReader();

            //2.解析xml文档
            Document document = sax.read("src/test.xml");

            //3.获得跟节点
            Element root = document.getRootElement();

            //4获取学生节点
            Element student = root.element("student");

            //5获取学生姓名节点
            Element name = student.element("name");
            System.out.println(name.getText());

            //获取学生属性编号的值
            Attribute attribute = name.attribute("id");
            System.out.println(attribute.getValue());

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
    /**
     * xpath获取xml标签的文本内容和属性值
     * @param args
     */
    @Test
    public void run2() {
        try {
            // 1. 先创建解析器对象
            SAXReader sax = new SAXReader();
            //2 .解析xml文档
            Document document = sax.read("src/test.xml");
            // document是Node的子节点,能使用node节点对象的方法
            Node node = document.selectSingleNode("//name");
            // 获取学生姓名
            System.out.println(node.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * xpath获取xml标签的文本内容和属性值
     * @param args
     */
    @Test
    public void run3() {
        try {
            SAXReader sax = new SAXReader();
            Document document = sax.read("src/test.xml");
            List selectNodes = document.selectNodes("//name");
            for (Node node : selectNodes) {
                System.out.println(node.getText());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

需要导入的jar包
dom和xpath解析xml



    
        张三