XML解析之xpath的使用

使用dom4j查询标签较多的xml文件时,需要不断的嵌套for循环。

基于dom4j,使用xpath可以简化查询

在dom4j里面提供了两个方法,用来支持xpath

List<Node> selectNodes("xpath表达式"),用来获取多个节点
Node selectSingleNode("xpath表达式"),用来获取一个节点

XML文件:

public class Demo01 {
    public static void main(String[] args) throws FileNotFoundException, DocumentException {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new FileInputStream("XML/src/beans.xml"));
        System.out.println(document);   //org.dom4j.tree.DefaultDocument@16b98e56 [Document: name null]

        //获取bean标签集合
        List<Node> bean = document.selectNodes("//bean");
        System.out.println(bean.size());    //2 有两个bean标签元素

        //查询所有property标签中Value属性的值
        List<Element> props = document.selectNodes("//property");
        for (Element prop : props) {
            String value = prop.attributeValue("value");
            System.out.println("value = " + value);
            System.out.println("--------");
        }

        //查询id=002的元素className的值
        Element ele = (Element)document.selectSingleNode("//bean[@id='002']");
        String className = ele.attributeValue("className");
        System.out.println(className);  //cn.itcast.demo.Admin
        /*
            获取到xml文件中的类名,就可以使用反射来进行一些操作了。
         */
    }
}

运行结果:

posted @ 2020-09-06 16:51  硬盘红了  阅读(337)  评论(0编辑  收藏  举报