XPath介绍

转自http://blog.chinaunix.net/u/24129/showart_311035.html

相关使用手册:http://www.zvon.org/xxl/XPathTutorial/General_chi/examples.html (介绍相关语法)

参考:http://www.microsoft.com/china/MSDN/library/data/xml/XPathintr.mspx?mfr=true

XPath 是一种用于寻址 XML 文档内容的语言

XPathisalanguageforfindinginformationinanXMLdocument.XPathisusedtonavigatethroughelementsandattributesinanXMLdocument.
Xpath是一种能够在XML文档中寻找信息的语言。它通过XML文档中的元素和属性来进行导航。


--------------------------------------------------------------------------------

WhatYouShouldAlreadyKnow
你应具备的知识
Beforeyoucontinueyoushouldhaveabasicunderstandingofthefollowing:
在你继续前你应该具备以下知识的基础:

HTML/XHTML
XML/XMLNamespaces[命名空间]

--------------------------------------------------------------------------------

WhatisXPath?
什么是XPath?
XPathisasyntaxfordefiningpartsofanXMLdocument
XPath是针对XML文档部分内容定义的语法
XPathusespathexpressionstonavigateinXMLdocuments
XPath使用路径表达式在XML文档中导航
XPathcontainsalibraryofstandardfunctions
XPath包含了一系列标准函数
XPathisamajorelementinXSLT
XPath在XSLT当中是一个主要的元素
XPathisaW3CStandard
XPath是W3C标准

--------------------------------------------------------------------------------

XPathPathExpressions
XPath路径表达式
XPathusespathexpressionstoselectnodesornode-setsinanXMLdocument.Thesepathexpressionslookverymuchliketheexpressionsyouseewhenyouworkwithatraditionalcomputerfilesystem.
XPath使用路径表达式来选择XML文档中的nodes(节)或是node-set(节集)。这些路径表达式看上去与你平时所见的传统计算机文件系统路径非常地相似。


--------------------------------------------------------------------------------

XPathStandardFunctions
XPath标准函数
XPathincludesover100built-infunctions.Therearefunctionsforstringvalues,numericvalues,dateandtimecomparison,nodeandQNamemanipulation,sequencemanipulation,Booleanvalues,andmore.
XPath包含了数量超过100的内置函数。这些函数针对字符串值,数字值,日期和时间比较,节操作,顺序操作,布尔值,等等。


--------------------------------------------------------------------------------

XPathisUsedinXSLT
XPath被用在XSLT
XPathisamajorelementintheXSLTstandard.WithoutXPathknowledgeyouwillnotbeabletocreateXSLTdocuments.
在XSLT标准中XPath是主要的元素。没有XPath知识你将很难建立XSLT文档。

XQueryandXPointerarebothbuiltonXPathexpressions.XQuery1.0andXPath2.0sharethesamedatamodelandsupportthesamefunctionsandoperators.
XQuery和XPointer都建立于XPath表达式。XQuery1.0和XPath2.0共享相同的数据模型并支持相同的函数和操作


--------------------------------------------------------------------------------

XPathisaW3CStandard
XPath是W3C标准
XPathbecameaW3CRecommendation16.November1999.
XPat于1999年11月16日成为W3C的推荐标准

XPathwasdesignedtobeusedbyXSLT,XPointerandotherXMLparsingsoftware.
XPath被设计成为用语XSLT,XPoniter以及其他XML解析的软件。

XPathNodes(节)

InXPath,therearesevenkindsofnodes:element,attribute,text,namespace,processing-instruction,comment,anddocument(root)nodes.
在XPath中有七种nodes(节):元素,属性,文字,命名空间,处理说明,注释,和文档(根)节。


--------------------------------------------------------------------------------

XPathTerminology
XPath术语
Nodes/节
InXPath,therearesevenkindsofnodes:element,attribute,text,namespace,processing-instruction,comment,anddocument(root)nodes.XMLdocumentsaretreatedastreesofnodes.Therootofthetreeiscalledthedocumentnode(orrootnode).
XML文档被视为数状的节。树的根部被称为文档的节(或根节)。

LookatthefollowingXMLdocument:
观察下面的XML文档:

<?xmlversion="1.0"encoding="ISO-8859-1"?>
<bookstore>
<book>
<titlelang="en">HarryPotter</title>
<author>JK.Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
ExampleofnodesintheXMLdocumentabove:
上面举例的XML文档的节有:

<bookstore>(documentnode)
<author>JK.Rowling</author>(elementnode)
lang="en"(attributenode)
Atomicvalues
原子值
Atomicvaluesarenodeswithnochildrenorparent.
原子值是那些没有子或父的节(无上下关系)。

Exampleofatomicvalues:
举例中的原子值:

JK.Rowling
"en"
Items
项目
Itemsareatomicvaluesornodes.
项目是原子值或节。


--------------------------------------------------------------------------------

RelationshipofNodes
节之间的关系
Parent/父
Eachelementandattributehasoneparent.
每个元素和属性有一父亲。

Inthefollowingexample;thebookelementistheparentofthetitle,author,year,andprice:
下面的举例中:book元素是title,author,year和price的父亲

<book>
<title>HarryPotter</title>
<author>JK.Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
Children/子
Elementnodesmayhavezero,oneormorechildren.
元素节可能有0个或多个子

Inthefollowingexample;thetitle,author,year,andpriceelementsareallchildrenofthebookelement:
下面的举例中:title,author,year和price元素都是book元素的子元素

<book>
<title>HarryPotter</title>
<author>JK.Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
Siblings/兄
Nodesthathavethesameparent.
指那些有相同父的

Inthefollowingexample;thetitle,author,year,andpriceelementsareallsiblings:
下面的举例中title,author,year,和price元素都为兄弟

<book>
<title>HarryPotter</title>
<author>JK.Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
Ancestors/祖
Anode'sparent,parent'sparent,etc.
节的父,父的父....都为祖

Inthefollowingexample;theancestorsofthetitleelementarethebookelementandthebookstoreelement:
下面的举例中:book元素和bookstore元素都为title元素的祖元素

<bookstore>
<book>
<title>HarryPotter</title>
<author>JK.Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
Descendants/孙
Anode'schildren,children'schildren,etc.
节的子,子的子...都为孙

Inthefollowingexample;descendantsofthebookstoreelementarethebook,title,author,year,andpriceelements:
下面的举例中:bookstore元素的孙有book,title,author,year以及price元素

<bookstore>
<book>
<title>HarryPotter</title>
<author>JK.Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
XPath语法

XPathusespathexpressionstoselectnodesornode-setsinanXMLdocument.Thenodeisselectedbyfollowingapathorsteps.
XPath使用路径表达式来选择XML文档的节或是节集。顺着路径或步骤来选择节。


--------------------------------------------------------------------------------

TheXMLExampleDocument
XML实例文档
WewillusethefollowingXMLdocumentintheexamplesbelow.
举例中我们将使用下面的XML文档

<?xmlversion="1.0"encoding="ISO-8859-1"?>
<bookstore>
<book>
<titlelang="eng">HarryPotter</title>
<price>29.99</price>
</book>
<book>
<titlelang="eng">LearningXML</title>
<price>39.95</price>
</book>
</bookstore>

--------------------------------------------------------------------------------

SelectingNodes
选择节
XPathusespathexpressionstoselectnodesinanXMLdocument.Thenodeisselectedbyfollowingapathorsteps.Themostusefulpathexpressionsarelistedbelow:
一些非常有用的路径表达式:

表达式描述
nodenameSelectsallchildnodesofthenode[选择所有目前节的子节]
/Selectsfromtherootnode[从根节进行选择]
//Selectsnodesinthedocumentfromthecurrentnodethatmatchtheselectionnomatterwheretheyare[选择文档中相吻合的节而不管其在文档的何处]
.Selectsthecurrentnode[选择当前节]
..Selectstheparentofthecurrentnode[当前节的父节]
@Selectsattributes[选择属性]

Examples
实例
Inthetablebelowwehavelistedsomepathexpressionsandtheresultoftheexpressions:
下面我们所列举的表格有路径表达式以及其结果:

路径表达式结果
bookstoreSelectsallthechildnodesofthebookstoreelement[选择所有bookstore元素的子节]
/bookstoreSelectstherootelementbookstore
Note:Ifthepathstartswithaslash(/)italwaysrepresentsanabsolutepathtoanelement!

[选择了bookstore的根元素。注意:如果路径的开始为(/)那此路径一定是到该元素的绝对路径]
bookstore/bookSelectsallbookelementsthatarechildrenofbookstore[选择了所有在bookstore的子元素book元素所包含的所有元素(其实就为bookstore里book元素所包含的元素)]
//bookSelectsallbookelementsnomatterwheretheyareinthedocument[选择所有为book元素的内容而不管book元素处于何处(有不同的父也没关系)]
bookstore//bookSelectsallbookelementsthataredescendantofthebookstoreelement,nomatterwheretheyareunderthebookstoreelement[在bookstore元素内所有含有book元素的元素内容(只要book元素的祖元素为bookstore元素那都符合条件)]
//@langSelectsallattributesthatarenamedlang[选择所有属性名为lang的属性]


--------------------------------------------------------------------------------

Predicates
谓语
Predicatesareusedtofindaspecificnodeoranodethatcontainsaspecificvalue.
谓语用来指定明确的节所含有的特殊的值

Predicatesarealwaysembeddedinsquarebrackets.
谓语被嵌入在中括号

Examples
举例
Inthetablebelowwehavelistedsomepathexpressionswithpredicatesandtheresultoftheexpressions:
下面的表格列举了一些使用了谓语的路径表达式以及其产生的结果:

路径表达式结果
/bookstore/book[1]Selectsthefirstbookelementthatisthechildofthebookstoreelement[选择了bookstore里的第一个book元素]
/bookstore/book[last()]Selectsthelastbookelementthatisthechildofthebookstoreelement[选择bookstore里最后一个book元素]
/bookstore/book[last()-1]Selectsthelastbutonebookelementthatisthechildofthebookstoreelement[bookstore中倒数第二个book元素]
/bookstore/book[position()<3]Selectsthefirsttwobookelementsthatarechildrenofthebookstoreelement[在bookstore中前两个book元素]
//title[@lang]Selectsallthetitleelementsthathaveanattributenamedlang[选择所有含有lang属性的title元素]
//title[@lang='eng']Selectsallthetitleelementsthathaveanattributenamedlangwithavalueof'eng'[选择所有含有lang属性并且值为eng的title元素]
/bookstore/book[price>35.00]Selectsallthebookelementsofthebookstoreelementthathaveapriceelementwithavaluegreaterthan35.00[选择所有bookstore中book元素里price元素内容大于35.00的book元素]
/bookstore/book[price>35.00]/titleSelectsallthetitleelementsofthebookelementsofthebookstoreelementthathaveapriceelementwithavaluegreaterthan35.00[选择bookstore中book的子元素title,并且其兄弟元素price的内容得大于35.00]


--------------------------------------------------------------------------------

SelectingUnknownNodes
选择未知的节
XPathwildcardscanbeusedtoselectunknownXMLelements.
XPath的通配符可以用来选择未知的XML元素

通配符描述
*Matchesanyelementnode[相吻合的所有元素节]
@*Matchesanyattributenode[相吻合的所有属性节]
node()Matchesanynodeofanykind[吻合任何类型的节]

Examples实例
Inthetablebelowwehavelistedsomepathexpressionsandtheresultoftheexpressions:
下面的表格我们将列举一些路径表达式以及它们的结果

路径表达式结果
/bookstore/*Selectsallthechildnodesofthebookstoreelement[选择所有bookstore的子节]
//*Selectsallelementsinthedocument[选择所有文档中的元素]
//title[@*]Selectsalltitleelementswhichhaveanyattribute[选择元素为title并且其含有属性]


--------------------------------------------------------------------------------

SelectingSeveralPaths
选择数个路径
Byusingthe|operatorinanXPathexpressionyoucanselectseveralpaths.
通过在XPath中使用|你可以选择数个路径

Examples
实例
Inthetablebelowwehavelistedsomepathexpressionsandtheresultoftheexpressions:
下面的表格我们会列举一些路径表达式以及其结果:

路径表达结果
//book/title|//book/priceSelectsallthetitleANDpriceelementsofallbookelements[选择所有book里title和price元素]
//title|//priceSelectsallthetitleANDpriceelementsinthedocument[选择所有title和price元素]
/bookstore/book/title|//priceSelectsallthetitleelementsofthebookelementofthebookstoreelementANDallthepriceelementsinthedocument[选择所有book里的title元素和所有price元素]

XPath轴


TheXMLExampleDocument
XML举例文档
WewillusethefollowingXMLdocumentintheexamplesbelow.
我么将使用该XML文档进行下面的举例说明

<?xmlversion="1.0"encoding="ISO-8859-1"?>
<bookstore>
<book>
<titlelang="eng">HarryPotter</title>
<price>29.99</price>
</book>
<book>
<titlelang="eng">LearningXML</title>
<price>39.95</price>
</book>
</bookstore>

--------------------------------------------------------------------------------

XPathAxes
XPath轴
Anaxisdefinesanode-setrelativetothecurrentnode.
轴定义了相对于当前节的节集

轴名结果
ancestorSelectsallancestors(parent,grandparent,etc.)ofthecurrentnode[选择了当前节的所有祖(父,祖父,等等)]
ancestor-or-selfSelectsallancestors(parent,grandparent,etc.)ofthecurrentnodeandthecurrentnodeitself[选择当前节的所有祖并且还有当前节自己]
attributeSelectsallattributesofthecurrentnode[选择所有当前节的属性]
childSelectsallchildrenofthecurrentnode[选择所有当前节的子]
descendantSelectsalldescendants(children,grandchildren,etc.)ofthecurrentnode[选择所有当前节的孙(子,孙子,等等)]
descendant-or-selfSelectsalldescendants(children,grandchildren,etc.)ofthecurrentnodeandthecurrentnodeitself[选择当前节的所有孙以及它本身]
followingSelectseverythinginthedocumentaftertheclosingtagofthecurrentnode[选择所有在关闭当前节标签后的所有内容]
following-siblingSelectsallsiblingsafterthecurrentnode[选择所有当前节后的兄]
namespaceSelectsallnamespacenodesofthecurrentnode[选择所有当前节的命名空间]
parentSelectstheparentofthecurrentnode[选择当前节的父]
precedingSelectseverythinginthedocumentthatisbeforethestarttagofthecurrentnode[选择当前节之前的所有内容]
preceding-siblingSelectsallsiblingsbeforethecurrentnode[选择所有当前节之前的兄]
selfSelectsthecurrentnode[选择当前节]


--------------------------------------------------------------------------------

LocationPathExpression
路径表达试定位
Alocationpathcanbeabsoluteorrelative.
定位路径可以是绝对的也可以是相对的

Anabsolutelocationpathstartswithaslash(/)andarelativelocationpathdoesnot.Inbothcasesthelocationpathconsistsofoneormoresteps,eachseparatedbyaslash:
绝对定位的路径由(/)开始,而相对定位就不这样。定位的路径由一个或多个步骤所组成,每部分由(/)相分隔:

Anabsolutelocationpath:
/step/step/...
Arelativelocationpath:
step/step/...
Eachstepisevaluatedagainstthenodesinthecurrentnode-set.
在当前的节集中每步的赋值是逆向的

Astepconsistsof:

anaxis(definesthetree-relationshipbetweentheselectednodesandthecurrentnode)
anode-test(identifiesanodewithinanaxis)[在轴中鉴定节]
zeroormorepredicates(tofurtherrefinetheselectednode-set)[0个或多个谓语可以来更好的选择节]
Thesyntaxforalocationstepis:
定位的语法

axisname::nodetest[predicate]
Examples
实例
Example结果
child::bookSelectsallbooknodesthatarechildrenofthecurrentnode[选择当前节点下所有为book的子节点]
attribute::langSelectsthelangattributeofthecurrentnode[选择当前节点下所有属性为lang的内容]
child::*Selectsallchildrenofthecurrentnode[选择当前节下所有的子节]
attribute::*Selectsallattributesofthecurrentnode[选择当前节所有的属性]
child::text()Selectsalltextchildnodesofthecurrentnode[选择当前节点所有子节点的文字]
child::node()Selectsallchildnodesofthecurrentnode[选择所有当前节点的子节点]
descendant::bookSelectsallbookdescendantsofthecurrentnode[选择当前节点所有为book的孙节点]
ancestor::bookSelectsallbookancestorsofthecurrentnode[选择所有当前祖节点为book的节点]
ancestor-or-self::bookSelectsallbookancestorsofthecurrentnode-andthecurrentaswellifitisabooknode[当前节点和其祖节点为book的节点]
child::*/child::priceSelectsallpricegrandchildrenofthecurrentnode[当前节点所有含price的孙子节点]


XPath运算符


AnXPathexpressionreturnseitheranode-set,astring,aBoolean,oranumber.


--------------------------------------------------------------------------------

XPathOperators
BelowisalistoftheoperatorsthatcanbeusedinXPathexpressions:

OperatorDescriptionExampleReturnvalue
|Computestwonode-sets//book|//cdReturnsanode-setwithallbookandcdelements
+Addition6+410
-Subtraction6-42
*Multiplication6*4
24
divDivision8div42
=Equalprice=9.80trueifpriceis9.80
falseifpriceis9.90
!=Notequalprice!=9.80trueifpriceis9.90
falseifpriceis9.80
<Lessthanprice<9.80trueifpriceis9.00
falseifpriceis9.80
<=Lessthanorequaltoprice<=9.80trueifpriceis9.00
falseifpriceis9.90
>Greaterthanprice>9.80trueifpriceis9.90
falseifpriceis9.80
>=Greaterthanorequaltoprice>=9.80trueifpriceis9.90
falseifpriceis9.70
ororprice=9.80orprice=9.70trueifpriceis9.80
falseifpriceis9.50
andandprice>9.00andprice<9.90trueifpriceis9.80
falseifpriceis8.50
modModulus(divisionremainder)5mod21

XPath实例


Let'strytolearnsomebasicXPathsyntaxbylookingatsomeexamples.
让我们来尝试通过观察一些实例来学习基础的XPath语法


--------------------------------------------------------------------------------

TheXMLExampleDocument
WewillusethefollowingXMLdocumentintheexamplesbelow.
我们将使用下面这个XML文档来进行实例

"books.xml":

<?xmlversion="1.0"encoding="ISO-8859-1"?>
<bookstore>
<bookcategory="COOKING">
<titlelang="en">EverydayItalian</title>
<author>GiadaDeLaurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<bookcategory="CHILDREN">
<titlelang="en">HarryPotter</title>
<author>JK.Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<bookcategory="WEB">
<titlelang="en">XQueryKickStart</title>
<author>JamesMcGovern</author>
<author>PerBothner</author>
<author>KurtCagle</author>
<author>JamesLinn</author>
<author>VaidyanathanNagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<bookcategory="WEB">
<titlelang="en">LearningXML</title>
<author>ErikT.Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
Viewthe"books.xml"fileinyourbrowser.


--------------------------------------------------------------------------------

SelectingNodes
选择节点
WewillusetheMicrosoftXMLDOMobjecttoloadtheXMLdocumentandtheselectNodes()functiontoselectnodesfromtheXMLdocument:
我们使用了XMLDOM对象来加载XML文档并用selectNode()函数来进行XML文档上节点的选择:

setxmlDoc=CreateObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load("books.xml")
xmlDoc.selectNodes(pathexpression)


--------------------------------------------------------------------------------

SelectallbookNodes
选择所有book节点
Thefollowingexampleselectsallthebooknodesunderthebookstoreelement:
下面这个实例就会选择所有bookstore元素以下的book节点:

xmlDoc.selectNodes("/bookstore/book")
如果你有IE5以上的版本你可以自己来做一下.


--------------------------------------------------------------------------------

SelecttheFirstbookNode
选择第一个book节点
Thefollowingexampleselectsonlythefirstbooknodeunderthebookstoreelement:

xmlDoc.selectNodes("/bookstore/book[0]")
IfyouhaveIE5orhigheryoucantryityourself.

Note:IE5and6hasimplementedthat[0]shouldbethefirstnode,butaccordingtotheW3Cstandarditshouldhavebeen[1]!!


--------------------------------------------------------------------------------

Selecttheprices
选择prices
Thefollowingexampleselectsthetextfromallthepricenodes:

xmlDoc.selectNodes("/bookstore/book/price/text()")
IfyouhaveIE5orhigheryoucantryityourself.


--------------------------------------------------------------------------------

SelectingpriceNodeswithPrice>35
选择price大于35的price节点
Thefollowingexampleselectsallthepricenodeswithapricehigherthan35:

xmlDoc.selectNodes("/bookstore/book[price>35]/price")
IfyouhaveIE5orhigheryoucantryityourself.


--------------------------------------------------------------------------------

SelectingtitleNodeswithPrice>35
选择Price大于35的title节点
Thefollowingexampleselectsallthetitlenodeswithapricehigherthan35:

xmlDoc.selectNodes("/bookstore/book[price>35]/title")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值