XPath具体解释

New Document

相关读书笔记、心得文章列表
一、结点类型
XPath中有七种结点类型: 元素、属性、文本、命名空间、处理指令、凝视以及文档节点(或成为根节点)。 文档的根节点即是文档结点;相应属性有属性结点,元素有元素结点。

二、经常使用路径表达式
表达式描写叙述
nodename                                     选取此节点的全部子节点
/                                     从根节点选取
//                                     从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置
.                                     选取当前节点
..                                     选取当前节点的父节点
@                                     选取属性
  比如有文档:
<?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <book> <title lang="eng">Harry Potter</title> <price>29.99</price> </book> <book> <title lang="eng">Learning XML</title> <price>39.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[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 * 424
div除法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。
orprice=9.80 or price=9.70 假设 price 是 9.80,则返回 true。 假设 price 是 9.50,则返回 fasle。
andprice>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代码
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类型强制转换成相应的返回类型。  
2. API的使用
相似于Dom,要得到一个Xpath对象,能够例如以下使用: Java代码
XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expression = xpath.compile("/bookstore//book/title/text()");
		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();
		XPathExpression expression = xpath.compile("/bookstore//book/title/text()");
还是以之前的xml文档为例。要得到这个表达式的结果,我们先要得到一个输入对象,比如一个document:
Java代码
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(new File("books.xml")); NodeList list = (NodeList) expression.evaluate(document,XPathConstants.NODESET);
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
		Document document = documentBuilder.parse(new File("books.xml"));
		NodeList list = (NodeList) expression.evaluate(document,XPathConstants.NODESET);
这里能够看出,在使用Xpath的时候,我们好像须要非常清楚的知道返回结果是什么。否则就不能得到意想的结果。
最后,我们得到一个title的list值:
Java代码
for(int i = 0;i<list.getLength();i++){ System.out.println(list.item(i).getNodeValue()); }
		for(int i = 0;i
Java代码
  1. Everyday Italian  
  2. Harry Potter  
  3. XQuery Kick Start  
  4. Learning XML  
Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML
八、处理命令空间
一般一个规范xml都会有命名空间的定义,比如:


          
          	Hello
          
  <?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:title>Hello</tg:title> </ns:book> </tg:bookstore> 
xpath中定义了与节点名和命名空间有关的三个函数:
  • local-name()
  • namespace-uri()
  • name()
比如要查找全部在当前文档中定义的,元素的local名为book的结点,则例如以下:
Java代码
XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xpath = xPathFactory.newXPath(); XPathExpression compile = xpath.compile("//*[local-name()='book']"); NodeList list = (NodeList) compile.evaluate(document,XPathConstants.NODESET);
		XPathFactory xPathFactory = XPathFactory.newInstance();
		XPath xpath = xPathFactory.newXPath();
		XPathExpression compile = xpath.compile("//*[local-name()='book']");
		NodeList list = (NodeList) compile.evaluate(document,XPathConstants.NODESET);
假设元素定义了命名空间,则使用xpath查找时也必须指定在同一个命名空间中,即便元素使用的是缺省的命名空间,刚查找也须要定义缺省的命名空间。 比如文档:
Xml代码
<?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:title>Hello</tg:title> </ns:book> <computer> <id>ElsIOIELdslke-1233</id> </computer> </bookstore>


          
          	Hello
          
          
               ElsIOIELdslke-1233
          
定义了三个命名空间:缺省的;xmlns:tg;xmlns:ns。 要使用命名空间,我们须要设置XPath的命名空间上下文:NamespaceContext。这是一个接口类型,我们须要自己定义去实现它。比如相应于上文档的三个命名空间,能够例如以下实现:
Java代码
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; } }
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;
		}
		
	}
方法名都很直观。这里仅仅实现第一个方法。 这样,假设要查找命名空间是缺省,元素名为computer的全部元素,能够例如以下实现:
Java代码
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()); }
		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
  九、其它
除此之外,在java中,还能够定义扩展的函数解释器和变量解释器,看XPath的方法:
Java代码
/** * 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);
    /**
     * 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);
详细的能够參看API帮助
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值