XML学习---Xpath学习

使用xpath的套路:
通过dom调用Node中的如下方法,每个方法中的参数用 “xpath表达式”—String型
selectNodes(xpath), selectSingleNode(xpath), selectObject(xpath)
selectNodes(String xpathExpression) :通过Xpath找到符合的元素,全按照返回出来
list:selectNodes(String xpathExpression, 比较XPath表达式的结果 排序 )
list:selectNodes(String xpathExpression, 排序参数, 是否删除重复)
object:selectObject(String xpathExpression):仅仅区别在于返回值是object
Node:selectSingleNode(String xpathExpression) 结果作为单个节点实例返回。
一个小细节: 以上3个方法是Node中的方法,因此任意节点都可以调用,
但所选择的却是document下面的所有符合xpath的节点或对象–不是当前调用节点子树范围(局部),而是整棵树(全局)
Xpath表达式几个要点

 @id: 表示属性,@属性
 last():最后一个
 not:表示不是这一个
 normalize-space函数去掉前后空格后
 count(BBB)=2:有2个BBB子元素的元素
 name()='BBB':所有名称为BBB的元素
 starts-with(name(),'B'):选择所有名称以"B"起始的元素
 contains(name(),'C'):选择所有名称包含"C"的元素
 child轴(axis)包含上下文节点的子元素, 作为默认的轴,可以忽略不写.
 child::AAA ==  /AAA  任意子树是AAA
  descendant 后代
  parent  父节点
  ancestor 祖先节点,
  following -sibling    弟弟节点
  preceding-sibling  哥哥节点
  following  下文所有的节点  ()
  preceding  上文所有节点
  descendant-or-self 自己+自己的后代
  ancestor-or-self  自己+自己的直系祖先
package cn.hncu.dom4j;

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


public class Xpath {

    public static void main(String[] args) throws Exception{
        Document dom = new SAXReader().read("./xml/contact.xml");
        String path = "//contact/aa";
        Node node = dom.selectSingleNode(path);
        System.out.println(node.getText());
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值