DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> XML學習教程 >> XML詳解 >> XPath介紹
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(節集)。這些路徑表達式看上去與你平時所見的傳統計算機文件系統路徑非常地相似。

 

在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

  andand price>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")



 

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved