xPath语法

来源:互联网 发布:巧克力键盘 知乎 编辑:程序博客网 时间:2024/06/06 09:19

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.Text;
import org.dom4j.io.SAXReader;

class Demo{
    public static void main(String[] args) throws Exception{
        Document doc = new SAXReader().read(new File("F:\\person.xml"));
        /*
         *   /  绝对路径
         *
         */
        String xPath;
        xPath = "/persons";
        xPath = "/persons/person";
        /*
         *   //  相对路径
         *
         */
        xPath = "//person";
        xPath = "//name";
        /*
         *
         *     *表示匹配所有的元素
         *
         */
        xPath = "/persons/*";
        xPath = "/persons//*";
        
        /*
         *
         *  [@xx]表示选取xx属性的person标签
         *
         */
        xPath = "//person[@id]";
        xPath = "//person[2]";
        xPath  = "//person[@id='001']";
        
        /*
         *
         *   text()表示选取文本内容
         *
         */
        xPath = "//name/text()";
        List <Node> list = doc.selectNodes(xPath);
        for(Node node:list) {
            System.out.println(node);
        }
        /**
         *
         *   and 表示[]中的条件且关系(类似&&)
         *   比如: //person[@id='001' and @name='xxx']
         *
         *
         */
    }
}