码迷,mamicode.com
首页 > 其他好文 > 详细

dom4j支持Xpath的具体操作

时间:2018-06-12 00:13:10      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:get   name   col   ctf   多个   system   print   ati   sele   

***默认情况下,dom4j不支持xpath。

  如果想要使用xpath,需要引入jaxen-1.1-beta-6.jar包。

在dom4j中提供了两个方法来支持xpath。

***selectNodes("xpath表达式")

    ---获取多个节点

***selectSingleNode("xpath表达式")

    ---获取一个节点

**使用xpath实现:查询所有name元素的值

    所有name元素的值用://name  

animal.xml

<?xml version="1.0" encoding="UTF-8"?>
<animal>
  <cat id1="sususu">
    <name>汤姆</name>  
    <color>black</color>  
    <age>30</age>  
    <sex>男</sex>
  </cat>  
  <friend>丫丫</friend>  
  <cat>
    <name>丑小鸭</name>  
    <color>yellow</color>  
    <age>15</age>
  </cat>
</animal>
dom4jXpath.java

package example4;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.Node;

public class dom4jXpath {
    public static void main(String[] args) {
        //selectName();
        selectFirstName();
    }
    //使用xpath获取所有
    public static void selectName() {
        //得到document对象
        Document document=dom4jClass.getDocument();
        List<Node> list=document.selectNodes("//age");
        //遍历list集合
        for (Node node : list) {
            String s=node.getText();
        System.out.println(s);
        }
    }
    //使用xpath获取第一个cat下面的name的值
    public static void selectFirstName() {
        Document document=dom4jClass.getDocument();
        Node node=document.selectSingleNode("//cat[@id1=‘sususu‘]/name");
        String s=node.getText();
        System.out.println(s);
    }
}

dom4j支持Xpath的具体操作

标签:get   name   col   ctf   多个   system   print   ati   sele   

原文地址:https://www.cnblogs.com/aasu/p/9170626.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!