XPath详解

来源:互联网 发布:mysql myql 主从好处 编辑:程序博客网 时间:2024/05/17 07:45
[java] view plaincopy
  1. import java.io.IOException;  
  2.   
  3. import javax.xml.parsers.*;  
  4. import javax.xml.xpath.*;  
  5. import org.w3c.dom.*;  
  6. import org.xml.sax.SAXException;  
  7.   
  8. public class XpathTest {  
  9.   
  10.     public static void main(String[] args) throws ParserConfigurationException,  
  11.             SAXException, IOException, XPathExpressionException {  
  12.         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
  13.         factory.setNamespaceAware(false);  
  14.         DocumentBuilder builder = factory.newDocumentBuilder();  
  15.         Document doc = builder.parse("C:/Users/Administrator/Desktop/test.xml");  
  16.         System.out.println(doc.getChildNodes().getLength());  
  17.         XPathFactory xFactory = XPathFactory.newInstance();  
  18.         XPath xpath = xFactory.newXPath();  
  19.         XPathExpression expr = xpath  
  20.                 .compile("//name/text()");  
  21.         Object result = expr.evaluate(doc, XPathConstants.NODESET);  
  22.         NodeList nodes = (NodeList) result;  
  23.         System.out.println(nodes.getLength());  
  24.         for (int i = 0; i < nodes.getLength(); i++) {  
  25.             System.out.println(nodes.item(i).getNodeValue());  
  26.         }  
  27.     }  
  28.   
  29. }  


一、结点类型
XPath中有七种结点类型:元素、属性、文本、命名空间、处理指令、注释以及文档节点(或成为根节点)。 文档的根节点即是文档结点;对应属性有属性结点,元素有元素结点。

二、常用路径表达式
表达式描述nodename                                     选取此节点的所有子节点/                                     从根节点选取//                                     从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置.                                     选取当前节点..                                     选取当前节点的父节点@                                     选取属性
  例如有文档:
[xhtml] view plaincopy
  1. <?xml version="1.0" encoding="ISO-8859-1"?>  
  2. <bookstore>  
  3. <book>  
  4.   <title lang="eng">Harry Potter</title>  
  5.   <price>29.99</price>  
  6. </book>  
  7. <book>  
  8.   <title lang="eng">Learning XML</title>  
  9.   <price>39.95</price>  
  10. </book>  
  11. </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[price>35.00]选取所有 bookstore 元素的 book 元素,且其中的 price 元素的值须大于 35.00。/bookstore/book[price>35.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 + 410-减法6 - 42*乘法6 * 424div除法8 div 42=等于price=9.80如果 price 是9.80,则返回 true。 如果 price 是9.90,则返回 fasle。!=不等于price!=9.80如果 price 是 9.90,则返回 true。 如果 price 是 9.98,则返回 fasle。<小于price<9.80如果price是9.00,则返回true 如果price是9.98,则返回fasle<=小于或等于price<=9.80如果 price 是9.00,则返回 true。 如果 price 是9.90,则返回 fasle。>大于price>9.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与price>9.00 and price<9.90如果 price 是 9.80,则返回 true。 如果 price 是 8.50,则返回 fasle。mod计算除法的余数5 mod 21 
七、在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代码
    [java] view plaincopy
    1.  public Object evaluate(Object item, QName returnType)throws XPathExpressionException;    
    2.     
    3. public String evaluate(Object item)throws XPathExpressionException;    
    4.     
    5. public Object evaluate(InputSource source, QName returnType)throws XPathExpressionException;    
    6.    
    7. public String evaluate(InputSource source)throws XPathExpressionException;    

    [java] view plaincopy
    1. public Object evaluate(Object item, QName returnType)throws XPathExpressionException;  
    2.   
    3. public String evaluate(Object item)throws XPathExpressionException;  
    4.   
    5. public Object evaluate(InputSource source, QName returnType)throws XPathExpressionException;  
    6.   
    7. public String evaluate(InputSource source)throws XPathExpressionException;  
    不指定返回类型时,缺省返回类型为String。指定返回类型时,需要把返回值由Object类型强制转换成对应的返回类型。  
    2. API的使用
    类似于Dom,要得到一个Xpath对象,可以如下使用: Java代码
    [java] view plaincopy
    1. XPathFactory factory = XPathFactory.newInstance();    
    2. XPath xpath = factory.newXPath();    
    3. XPathExpression expression = xpath.compile("/bookstore//book/title/text()");    

    [java] view plaincopy
    1. <strong><strong>        XPathFactory factory = XPathFactory.newInstance();  
    2.         XPath xpath = factory.newXPath();  
    3.         XPathExpression expression = xpath.compile("/bookstore//book/title/text()");</strong></strong>  
    还是以之前的xml文档为例。要得到这个表达式的结果,我们先要得到一个输入对象,例如一个document:
    Java代码
    [java] view plaincopy
    1. DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();    
    2. DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();    
    3. Document document = documentBuilder.parse(new File("books.xml"));    
    4. NodeList list = (NodeList) expression.evaluate(document,XPathConstants.NODESET);    

    [java] view plaincopy
    1. <strong><strong>        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();  
    2.         DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();  
    3.         Document document = documentBuilder.parse(new File("books.xml"));  
    4.         NodeList list = (NodeList) expression.evaluate(document,XPathConstants.NODESET);</strong></strong>  
    这里可以看出,在使用Xpath的时候,我们好像需要很清楚的知道返回结果是什么。否则就不能得到意想的结果。 
    最后,我们得到一个title的list值:
    Java代码
    [java] view plaincopy
    1. for(int i = 0;i<list.getLength();i++){                System.out.println(list.item(i).getNodeValue());    
    2. }  

    [java] view plaincopy
    1. <strong><strong>        for(int i = 0;i</strong></strong>  
    Java代码 
    1. Everyday Italian  
    2. Harry Potter  
    3. XQuery Kick Start  
    4. Learning XML  
    [java] view plaincopy
    1. <strong><strong>Everyday Italian  
    2. Harry Potter  
    3. XQuery Kick Start  
    4. Learning XML</strong></strong>  
  • 八、处理命令空间
    一般一个规范xml都会有命名空间的定义,例如:
    [xml] view plaincopy
    1. <strong><strong>  
    2.   
    3.             
    4.             Hello  
    5.             
    6. </strong></strong>  
     
    [java] view plaincopy
    1. <?xml version="1.0" encoding="UTF-8"?>    
    2. <tg:bookstore xmlns:tg="http://www.tibco.com/cdc/liugang"    
    3.            xmlns:ns="http://www.tibco.com/cdc/liugang/ns">    
    4.           <ns:book>    
    5.             <tg:title>Hello</tg:title>    
    6.           </ns:book>    
    7. </tg:bookstore>  
     
    xpath中定义了与节点名和命名空间有关的三个函数:
    • local-name()
    • namespace-uri()
    • name()
    例如要查找所有在当前文档中定义的,元素的local名为book的结点,则如下:
    Java代码
    [java] view plaincopy
    1. XPathFactory xPathFactory = XPathFactory.newInstance();    
    2. XPath xpath = xPathFactory.newXPath();    
    3. XPathExpression compile = xpath.compile("//*[local-name()='book']");    
    4. NodeList list = (NodeList) compile.evaluate(document,XPathConstants.NODESET);    

    [java] view plaincopy
    1. <strong><strong>        XPathFactory xPathFactory = XPathFactory.newInstance();  
    2.         XPath xpath = xPathFactory.newXPath();  
    3.         XPathExpression compile = xpath.compile("//*[local-name()='book']");  
    4.         NodeList list = (NodeList) compile.evaluate(document,XPathConstants.NODESET);</strong></strong>  
    如果元素定义了命名空间,则使用xpath查找时也必须指定在同一个命名空间中,即便元素使用的是缺省的命名空间,刚查找也需要定义缺省的命名空间。 例如文档:
    Xml代码
    [xhtml] view plaincopy
    1. <?xml version="1.0" encoding="UTF-8"?>    
    2. <bookstore xmlns="http://www.tibco.com/cdc/liugang" xmlns:tg="http://www.tibco.com/cdc/liugang/tg"    
    3.            xmlns:ns="http://www.tibco.com/cdc/liugang/ns">    
    4.           <ns:book>    
    5.             <tg:title>Hello</tg:title>    
    6.           </ns:book>    
    7.           <computer>    
    8.                <id>ElsIOIELdslke-1233</id>    
    9.           </computer>    
    10. </bookstore>  

    [xml] view plaincopy
    1. <strong><strong>  
    2.   
    3.             
    4.             Hello  
    5.             
    6.             
    7.                ElsIOIELdslke-1233  
    8.             
    9. </strong></strong>  
    定义了三个命名空间:缺省的;xmlns:tg;xmlns:ns。 要使用命名空间,我们需要设置XPath的命名空间上下文:NamespaceContext。这是一个接口类型,我们需要自定义去实现它。例如对应于上文档的三个命名空间,可以如下实现:
    Java代码
    [java] view plaincopy
    1. class CustomNamespaceContext implements NamespaceContext{    
    2.     
    3.         public String getNamespaceURI(String prefix) {    
    4.             if(prefix.equals("ns")){    
    5.                 return "http://www.tibco.com/cdc/liugang/ns";    
    6.             }else if(prefix.equals("tg")){    
    7.                 return "http://www.tibco.com/cdc/liugang/tg";    
    8.             }else if(prefix.equals("df")){    
    9.                 return "http://www.tibco.com/cdc/liugang";    
    10.             }    
    11.             return XMLConstants.NULL_NS_URI;    
    12.         }    
    13.     
    14.         public String getPrefix(String namespaceURI) {    
    15.             return null;    
    16.         }    
    17.     
    18.         public Iterator getPrefixes(String namespaceURI) {    
    19.             return null;    
    20.         }    
    21.             
    22.     }    

    [java] view plaincopy
    1. <strong><strong>class CustomNamespaceContext implements NamespaceContext{  
    2.   
    3.         public String getNamespaceURI(String prefix) {  
    4.             if(prefix.equals("ns")){  
    5.                 return "http://www.tibco.com/cdc/liugang/ns";  
    6.             }else if(prefix.equals("tg")){  
    7.                 return "http://www.tibco.com/cdc/liugang/tg";  
    8.             }else if(prefix.equals("df")){  
    9.                 return "http://www.tibco.com/cdc/liugang";  
    10.             }  
    11.             return XMLConstants.NULL_NS_URI;  
    12.         }  
    13.   
    14.         public String getPrefix(String namespaceURI) {  
    15.             return null;  
    16.         }  
    17.   
    18.         public Iterator getPrefixes(String namespaceURI) {  
    19.             return null;  
    20.         }  
    21.           
    22.     }</strong></strong>  
    方法名都非常直观。这里只实现第一个方法。 这样,如果要查找命名空间是缺省,元素名为computer的所有元素,可以如下实现:
    Java代码
    [java] view plaincopy
    1. XPathFactory xPathFactory = XPathFactory.newInstance();    
    2. XPath xpath = xPathFactory.newXPath();    
    3. xpath.setNamespaceContext(new CustomNamespaceContext());    
    4. XPathExpression compile = xpath.compile("//df:computer");    
    5. NodeList list = (NodeList) compile.evaluate(document,XPathConstants.NODESET);    
    6. for(int i = 0;i  
    7.     Node item = list.item(i);    
    8.     System.out.println(item.getNodeName()+"  "+item.getNodeValue());    
    9. }    

    [java] view plaincopy
    1. <strong><strong>        XPathFactory xPathFactory = XPathFactory.newInstance();  
    2.         XPath xpath = xPathFactory.newXPath();  
    3.         xpath.setNamespaceContext(new CustomNamespaceContext());  
    4.         XPathExpression compile = xpath.compile("//df:computer");  
    5.         NodeList list = (NodeList) compile.evaluate(document,XPathConstants.NODESET);  
    6.         for(int i = 0;i</strong></strong>  
      九、其他
    除此之外,在java中,还可以定义扩展的函数解释器和变量解释器,看XPath的方法:
    Java代码
    [java] view plaincopy
    1.     /**  
    2.      *  
    3. Establish a variable resolver. 
    4.   
    5.      *   
    6.      *  
    7. A NullPointerException is thrown if resolver is null. 
    8.   
    9.      *   
    10.      * @param resolver Variable resolver.  
    11.      *   
    12.      *  @throws NullPointerException If resolver is null.  
    13.      */    
    14.     public void setXPathVariableResolver(XPathVariableResolver resolver);    
    15.     
    16.     
    17.     /**  
    18.        *  
    19. Establish a function resolver. 
    20.   
    21.        *   
    22.        *  
    23. A NullPointerException is thrown if resolver is null. 
    24.   
    25.        *   
    26.        * @param resolver XPath function resolver.  
    27.        *   
    28.        * @throws NullPointerException If resolver is null.  
    29.        */    
    30.     public void setXPathFunctionResolver(XPathFunctionResolver resolver);   
    [java] view plaincopy
    1. <strong><strong>    /** 
    2.      * Establish a variable resolver. 
    3.      *  
    4.      * A <code>NullPointerException</code> is thrown if <code>resolver</code> is <code>null</code>. 
    5.      *  
    6.      * @param resolver Variable resolver. 
    7.      *  
    8.      *  @throws NullPointerException If <code>resolver</code> is <code>null</code>. 
    9.      */  
    10.     public void setXPathVariableResolver(XPathVariableResolver resolver);  
    11.   
    12.   
    13.     /** 
    14.        * Establish a function resolver. 
    15.        *  
    16.        * A <code>NullPointerException</code> is thrown if <code>resolver</code> is <code>null</code>. 
    17.        *  
    18.        * @param resolver XPath function resolver. 
    19.        *  
    20.        * @throws NullPointerException If <code>resolver</code> is <code>null</code>. 
    21.        */  
    22.     public void setXPathFunctionResolver(XPathFunctionResolver resolver);</strong></strong>  
    转载自:http://blog.csdn.net/jefferxun1/article/details/7805062
    0 0
    原创粉丝点击