深入XPath的详解以及Java示例代码分析

2016-02-19 09:20 67 1 收藏

今天图老师小编给大家介绍下深入XPath的详解以及Java示例代码分析,平时喜欢深入XPath的详解以及Java示例代码分析的朋友赶紧收藏起来吧!记得点赞哦~

【 tulaoshi.com - 编程语言 】

代码如下:

import java.io.IOException;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class XpathTest {
 public static void main(String[] args) throws ParserConfigurationException,
   SAXException, IOException, XPathExpressionException {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(false);
  DocumentBuilder builder = factory.newDocumentBuilder();
  Document doc = builder.parse("C:/Users/Administrator/Desktop/test.xml");
  System.out.println(doc.getChildNodes().getLength());
  XPathFactory xFactory = XPathFactory.newInstance();
  XPath xpath = xFactory.newXPath();
  XPathExpression expr = xpath
    .compile("//name/text()");
  Object result = expr.evaluate(doc, XPathConstants.NODESET);
  NodeList nodes = (NodeList) result;
  System.out.println(nodes.getLength());
  for (int i = 0; i nodes.getLength(); i++) {
   System.out.println(nodes.item(i).getNodeValue());
  }
 }
}

一、结点类型
XPath中有七种结点类型:元素、属性、文本、命名空间、处理指令、注释以及文档节点(或成为根节点)。 文档的根节点即是文档结点;对应属性有属性结点,元素有元素结点。
二、常用路径表达式
表达式 描述
nodename      选取此节点的所有子节点
/             从根节点选取
//  从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置
.   选取当前节点
..    选取当前节点的父节点
@     选取属性
例如有文档:
代码如下:

?xml version="1.0" encoding="ISO-8859-1"? 
bookstore 
book 
  title lang="eng"Harry Potter/title 
  price29.99/price 
/book 
book 
  title lang="eng"Learning XML/title 
  price39.95/price 
/book 
/bookstore 

则:
路径表达式 结果
bookstore 选取 bookstore 元素的所有子节点
/bookstore 选取根元素 bookstore 注释:假如路径起始于正斜杠( / ),则此路径始终代表到某元素的绝对路径!
bookstore/book 选取所有属于 bookstore 的子元素的 book 元素。
//book 选取所有 book 子元素,而不管它们在文档中的位置。
bookstore//book 选择所有属于 bookstore 元素的后代的 book 元素,而不管它们位于 bookstore 之下的什么位置。
//@lang 选取所有名为 lang 的属性。
三、限定语
用来查找某个特定的节点或者包含某个指定的值的节点。以方括号括起。
例如:
路径表达式 结果
/bookstore/book[1] 选取属于 bookstore 子元素的第一个 book 元素。
/bookstore/book[last()] 选取属于 bookstore 子元素的最后一个 book 元素。
/bookstore/book[last()-1] 选取属于 bookstore 子元素的倒数第二个 book 元素。
/bookstore/book[position()3] 选取最前面的两个属于 bookstore 元素的子元素的 book 元素。
//title[@lang] 选取所有拥有名为 lang 的属性的 title 元素。
//title[@lang='eng'] 选取所有 title 元素,且这些元素拥有值为 eng 的 lang 属性。
/bookstore/book[price35.00] 选取所有 bookstore 元素的 book 元素,且其中的 price 元素的值须大于 35.00。
/bookstore/book[price35.00]/title 选取所有 bookstore 元素中的 book 元素的 title 元素,且其中的 price 元素的值须大于 35.00。
四、通配符
通配符 描述
* 匹配任何元素节点
@* 匹配任何属性节点
node() 匹配任何类型的节点
|          选取若干路径 
例如:
路径表达式 结果
/bookstore/* 选取 bookstore 元素的所有子节点
//* 选取文档中的所有元素
//title[@*] 选取所有带有属性的 title 元素。
//book/title | //book/price 选取所有 book 元素的 tilte 和 price 元素。
//title | //price 选取所有文档中的 title 和 price 元素。
/bookstore/book/title | //price 选取所有属于 bookstore 元素的 book 元素的 title 元素,以及文档中所有的 price 元素。

五、函数
名称 结果
ancestor 选取当前节点的所有先辈(父、祖父等)
ancestor-or-self 选取当前节点的所有先辈(父、祖父等)以及当前节点本身
attribute 选取当前节点的所有属性
child 选取当前节点的所有子元素。
descendant 选取当前节点的所有后代元素(子、孙等)。
descendant-or-self 选取当前节点的所有后代元素(子、孙等)以及当前节点本身。
following 选取文档中当前节点的结束标签之后的所有节点。
namespace 选取当前节点的所有命名空间节点
parent 选取当前节点的父节点。
preceding 选取文档中当前节点的开始标签之前的所有节点。
preceding-sibling 选取当前节点之前的所有同级节点。
self 选取当前节点。
路径表达式可以是绝对路径,也可以是相对路径。例如:
绝对位置路径:
/step/step/...相对位置路径:
step/step/...其中的每一步又可以是一个表达式,包括:
轴(函数)(axis)
定义所选节点与当前节点之间的树关系
节点测试(node-test)
识别某个轴内部的节点
零个或者更多谓语(predicate)
更深入地提炼所选的节点集
例如: 例子 结果
child::book 选取所有属于当前节点的子元素的 book 节点
attribute::lang 选取当前节点的 lang 属性
child::* 选取当前节点的所有子元素
attribute::* 选取当前节点的所有属性
child::text() 选取当前节点的所有文本子节点
child::node() 选取当前节点的所有子节点
descendant::book 选取当前节点的所有 book 后代
ancestor::book 选择当前节点的所有 book 先辈
ancestor-or-self::book 选取当前节点的所有book先辈以及当前节点(假如此节点是book节点的话)
child::*/child::price 选取当前节点的所有 price 孙。
六、运算符
运算符 描述 实例 返回值
| 计算两个节点集 //book | //cd 返回所有带有 book 和 ck 元素的节点集
+ 加法 6 + 4 10
- 减法 6 - 4 2
* 乘法 6 * 4 24
div 除法 8 div 4 2
= 等于 price=9.80 如果 price 是9.80,则返回 true。 如果 price 是9.90,则返回 fasle。
!= 不等于 price!=9.80 如果 price 是 9.90,则返回 true。 如果 price 是 9.98,则返回 fasle。
小于 price9.80 如果price是9.00,则返回true 如果price是9.98,则返回fasle
= 小于或等于 price=9.80 如果 price 是9.00,则返回 true。 如果 price 是9.90,则返回 fasle。
大于 price9.80 如果 price 是 9.90,则返回 true。 如果 price 是 9.80,则返回 fasle。
= 大于或等于 price=9.80 如果 price 是 9.90,则返回 true。 如果 price 是 9.70,则返回 fasle。
or 或 price=9.80 or price=9.70 如果 price 是 9.80,则返回 true。 如果 price 是 9.50,则返回 fasle。
and 与 price9.00 and price9.90 如果 price 是 9.80,则返回 true。 如果 price 是 8.50,则返回 fasle。
mod 计算除法的余数 5 mod 2 1

七、在Java中使用Xpath
在java1.5中推出了一个javax.xml.xpath包专门用来在java中使用Xpath表达式来读取xml。1. 数据类型
在学习之前首先需要注意的是:Xpath的数据并不与Java有一一对应关系,Xpath1.0只声明了四种数据类型:
•node-set
•number
•boolean
•string

对应到java就是:
•number 映射为 java.lang.Double
•string 映射为 java.lang.String
•boolean 映射为 java.lang.Boolean
•node-set 映射为 org.w3c.dom.NodeList

因此,在使用java的xpathAPI时,需要注意返回类型:
Java代码
代码如下:

public Object evaluate(Object item, QName returnType)throws XPathExpressionException;   

public String evaluate(Object item)throws XPathExpressionException;   

public Object evaluate(InputSource source, QName returnType)throws XPathExpressionException;   

public String evaluate(InputSource source)throws XPathExpressionException;

代码如下:

public Object evaluate(Object item, QName returnType)throws XPathExpressionException; 

public String evaluate(Object item)throws XPathExpressionException; 

public Object evaluate(InputSource source, QName returnType)throws XPathExpressionException; 

public String evaluate(InputSource source)throws XPathExpressionException; 

不指定返回类型时,缺省返回类型为String。指定返回类型时,需要把返回值由Object类型强制转换成对应的返回类型。 
 API的使用
类似于Dom,要得到一个Xpath对象,可以如下使用: Java代码
代码如下:

XPathFactory factory = XPathFactory.newInstance();   
XPath xpath = factory.newXPath();   
XPathExpression expression = xpath.compile("/bookstore//book/title/text()");

代码如下:

strongstrong        XPathFactory factory = XPathFactory.newInstance(); 
        XPath xpath = factory.newXPath(); 
        XPathExpression expression = xpath.compile("/bookstore//book/title/text()");/strong/strong 

还是以之前的xml文档为例。要得到这个表达式的结果,我们先要得到一个输入对象,例如一个document:
代码如下:

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();   
DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();   
Document document = documentBuilder.parse(new File("books.xml"));   
NodeList list = (NodeList) expression.evaluate(document,XPathConstants.NODESET);   

代码如下:

strongstrong        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 
        DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); 
        Document document = documentBuilder.parse(new File("books.xml")); 
        NodeList list = (NodeList) expression.evaluate(document,XPathConstants.NODESET);/strong/strong 

这里可以看出,在使用Xpath的时候,我们好像需要很清楚的知道返回结果是什么。否则就不能得到意想的结果。
最后,我们得到一个title的list值:
代码如下:

for(int i = 0;ilist.getLength();i++){                System.out.println(list.item(i).getNodeValue());   


代码如下:

strongstrong        for(int i = 0;i/strong/strong 

代码如下:

Everyday Italian 
Harry Potter 
XQuery Kick Start 
Learning XML 

代码如下:

strongstrongEveryday Italian 
Harry Potter 
XQuery Kick Start 
Learning XML/strong/strong 

八、处理命令空间一般一个规范xml都会有命名空间的定义,例如:
代码如下:

strongstrong 

           
            Hello 

/strong/strong 

代码如下:

?xml version="1.0" encoding="UTF-8"?   
tg:bookstore xmlns:tg="http://www.tibco.com/cdc/liugang"   
           xmlns:ns="http://www.tibco.com/cdc/liugang/ns"   
          ns:book   
            tg:titleHello/tg:title   
          /ns:book   
/tg:bookstore 

xpath中定义了与节点名和命名空间有关的三个函数:
•local-name()
•namespace-uri()
•name()
例如要查找所有在当前文档中定义的,元素的local名为book的结点,则如下:
代码如下:

XPathFactory xPathFactory = XPathFactory.newInstance();   
XPath xpath = xPathFactory.newXPath();   
XPathExpression compile = xpath.compile("//*[local-name()='book']");   
NodeList list = (NodeList) compile.evaluate(document,XPathConstants.NODESET);   

代码如下:

strongstrong        XPathFactory xPathFactory = XPathFactory.newInstance(); 
        XPath xpath = xPathFactory.newXPath(); 
        XPathExpression compile = xpath.compile("//*[local-name()='book']"); 
        NodeList list = (NodeList) compile.evaluate(document,XPathConstants.NODESET);/strong/strong

如果元素定义了命名空间,则使用xpath查找时也必须指定在同一个命名空间中,即便元素使用的是缺省的命名空间,刚查找也需要定义缺省的命名空间。 例如文档:
代码如下:

?xml version="1.0" encoding="UTF-8"?   
bookstore xmlns="http://www.tibco.com/cdc/liugang" xmlns:tg="http://www.tibco.com/cdc/liugang/tg"   
           xmlns:ns="http://www.tibco.com/cdc/liugang/ns"   
          ns:book   
            tg:titleHello/tg:title   
          /ns:book   
          computer   
               idElsIOIELdslke-1233/id   
          /computer   
/bookstore 

代码如下:

strongstrong 

           
            Hello 

           
               ElsIOIELdslke-1233 

/strong/strong 

定义了三个命名空间:缺省的;xmlns:tg;xmlns:ns。 要使用命名空间,我们需要设置XPath的命名空间上下文:NamespaceContext。这是一个接口类型,我们需要自定义去实现它。例如对应于上文档的三个命名空间,可以如下实现:
代码如下:

class CustomNamespaceContext implements NamespaceContext{   

        public String getNamespaceURI(String prefix) {   
            if(prefix.equals("ns")){   
                return "http://www.tibco.com/cdc/liugang/ns";   
            }else if(prefix.equals("tg")){   
                return "http://www.tibco.com/cdc/liugang/tg";   
            }else if(prefix.equals("df")){   
                return "http://www.tibco.com/cdc/liugang";   
            }   
            return XMLConstants.NULL_NS_URI;   
        }   

        public String getPrefix(String namespaceURI) {   
            return null;   
        }   

        public Iterator getPrefixes(String namespaceURI) {   
            return null;   
        }   

    }   

代码如下:

strongstrongclass CustomNamespaceContext implements NamespaceContext{ 

        public String getNamespaceURI(String prefix) { 
            if(prefix.equals("ns")){ 
                return "http://www.tibco.com/cdc/liugang/ns"; 
            }else if(prefix.equals("tg")){ 
                return "http://www.tibco.com/cdc/liugang/tg"; 
            }else if(prefix.equals("df")){ 
                return "http://www.tibco.com/cdc/liugang"; 
            } 
            return XMLConstants.NULL_NS_URI; 
        } 

        public String getPrefix(String namespaceURI) { 
            return null; 
        } 

        public Iterator getPrefixes(String namespaceURI) { 
            return null; 
        } 

    }/strong/strong 

方法名都非常直观。这里只实现第一个方法。 这样,如果要查找命名空间是缺省,元素名为computer的所有元素,可以如下实现:
代码如下:

XPathFactory xPathFactory = XPathFactory.newInstance();   
XPath xpath = xPathFactory.newXPath();   
xpath.setNamespaceContext(new CustomNamespaceContext());   
XPathExpression compile = xpath.compile("//df:computer");   
NodeList list = (NodeList) compile.evaluate(document,XPathConstants.NODESET);   
for(int i = 0;i 
    Node item = list.item(i);   
    System.out.println(item.getNodeName()+"  "+item.getNodeValue());   
}   

代码如下:

strongstrong        XPathFactory xPathFactory = XPathFactory.newInstance(); 
        XPath xpath = xPathFactory.newXPath(); 
        xpath.setNamespaceContext(new CustomNamespaceContext()); 
        XPathExpression compile = xpath.compile("//df:computer"); 
        NodeList list = (NodeList) compile.evaluate(document,XPathConstants.NODESET); 
        for(int i = 0;i/strong/strong 

九、其他
除此之外,在java中,还可以定义扩展的函数解释器和变量解释器,看XPath的方法:
代码如下:

    /** 
     * 
Establish a variable resolver.

     *  
     * 
A NullPointerException is thrown if resolver is null.

     *  
     * @param resolver Variable resolver. 
     *  
     *  @throws NullPointerException If resolver is null. 
     */   
    public void setXPathVariableResolver(XPathVariableResolver resolver);   

   
    /** 
       * 
Establish a function resolver.

       *  
       * 
A NullPointerException is thrown if resolver is null.

       *  
       * @param resolver XPath function resolver. 
       *  
       * @throws NullPointerException If resolver is null. 
       */   
    public void setXPathFunctionResolver(XPathFunctionResolver resolver);  

代码如下:

strongstrong    /**
     * Establish a variable resolver.
     * 
     * A codeNullPointerException/code is thrown if coderesolver/code is codenull/code.
     * 
     * @param resolver Variable resolver.
     * 
     *  @throws NullPointerException If coderesolver/code is codenull/code.
     */ 
    public void setXPathVariableResolver(XPathVariableResolver resolver); 

 
    /**
       * Establish a function resolver.
       * 
       * A codeNullPointerException/code is thrown if coderesolver/code is codenull/code.
       * 
       * @param resolver XPath function resolver.
       * 
       * @throws NullPointerException If coderesolver/code is codenull/code.
       */ 
    public void setXPathFunctionResolver(XPathFunctionResolver resolver);/strong/strong 

来源:https://www.tulaoshi.com/n/20160219/1590409.html

延伸阅读
有时候,我们需要把对象A的所有值复制给对象B(B = A),但是这样用等号给赋值你会发现,当B中的某个对象值改变时,同时也会修改到A中相应对象的值! 也许你会说,用clone()不就行了?!你的想法只对了一半,因为用clone()时,除了基础数据和String类型的不受影响外,其他复杂类型(如集合、对象等)还是会受到影响的!除非你对每个对象里的复...
在Java 5.0之前启动一个任务是通过调用Thread类的start()方法来实现的,任务的提于交和执行是同时进行的,如果你想对任务的执行进行调度或是控制 同时执行的线程数量就需要额外编写代码来完成。5.0里提供了一个新的任务执行架构使你可以轻松地调度和控制任务的执行,并且可以建立一个类似数据库连接 池的线程池来执行任务。这个架构主要有三个接...
当你要做一个图库的项目时,对图片大小、像素的控制是首先需要解决的难题。 一、单图生成略缩图 单图经过重新绘制,生成新的图片。新图可以按一定比例由旧图缩小,也可以规定其固定尺寸。 详细代码如下: 代码如下: SPAN style="FONT-SIZE: 14px"import com.sun.image.codec.jpeg.JPEGImageEncoder; import com.sun.image.codec.jpeg.JP...
标签: Web开发
    相信用过google的analytics的朋友都了解其功能的强大.     由于工作需要,最近将其urchin.js的代码down了一份下来研究了一下.由于其注释很少,命名也很难读懂.研究了1个月.小有所成.将其代码重写并加上了注释.与大家一同分享.这里面将google的用户识别代码删除. /**//*  ===================...
标签: Web开发
1 异常 javax.servlet.jsp.JspException: Cannot retrieve mapping for action /Login (/Login是你的action名字) 可能原因:action没有再struts-config.xml 中定义,或没有找到匹配的action,例如在JSP文件中使用 处理:如果出现上述异常,请查看struts-config.xml中的定义部分,有时可能是打错了字符或者是某些不符合规则,可以使用struts con...

经验教程

339

收藏

7
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部