Showing posts with label html. Show all posts
Showing posts with label html. Show all posts

Friday, June 24, 2011

xPath

XPath is an emerging standard for directly accessing one or more nodes in an XML document using a simple filename-like syntax. For example, the XPath "/*/author" would select all of the grandchildren named "author", starting the search at the top-level document. Electric XML includes a useful subset of XPath functionality, and supports the following special tokens:

name
matches all nodes on the current level with the specified name
[n]
matches the nth node on the current level, with n=1 denoting the first node
name[n]
matches the nth element on the current level with the specified name
*
matches all nodes on the current level
/
if used as the first character, denotes the top-level document, otherwise denotes moving down a level
..
go up one level
.
the current level
//
the current level and all sublevels to any depth
[@key='value']
all elements with an attribute that matches the specified key/value pair
name[@key='value']
all elements with the specified name and an attribute that matches the specified key/value pair
[text()='value']
all elements with the specified text
name[text()='value']
all elements with the specified name and text
@name
the attribute with the specified name
@*
all attributes

定位節點
XML
是樹狀結構,類似檔案系統內資料夾的結構,XPath也類似檔案系統的路徑命名方式。不過XPath 是一種模式(Pattern),可以選出 XML檔案中,路徑符合某個模式的所有節點出來。
例如要選
catalog底下的cd中所有price元素可以用: /catalog/cd/price
如果XPath的開頭是一個斜線(/)代表這是絕對路徑。如果開頭是兩個斜線(//)表示檔中所有符合模式的元素都會被選出來,即使是處於樹中不同的層級也會被選出來。
以下的語法會選出檔中所有叫做
cd的元素(在樹中的任何層級都會被選出來):
//cd

選擇未知的元素
使用星號(Wildcards,*)可以選擇未知的元素。
下面這個語法會選出
/catalog/cd 的所有子元素:
/catalog/cd/*
以下的語法會選出所有catalog的子元素中,包含有price作為子元素的元素。
/catalog/*/price
以下的語法會選出有兩層父節點,叫做price的所有元素。
/*/*/price
以下的語法會選擇出檔中的所有元素。
//*

要注意的是,想要存取不分層級的元素,XPath語法必須以兩個斜線開頭(//),想要存取未知元素才用星號(*),星號只能代表未知名稱的元素,不能代表未知層級的元素。

選擇分支
使用中括弧可以選擇分支。以下的語法從catalog的子元素中取出第一個叫做cd的元素。XPath的定義中沒有第0元素這種東西。
/catalog/cd[1]
以下語法選擇catalog中的最後一個cd元素:(XPathj並沒有定義 first() 這種函式喔,用上例的 [1]就可以取出第一個元素。
/catalog/cd[last()]
以下語法選出含有price子元素的所有/catalog/cd元素。
/catalog/cd[price]
以下語法選出price元素的值等於10.90的所有/catalog/cd元素
/catalog/cd[price=10.90]
以下語法選出price元素的值等於10.90的所有/catalog/cd元素 price元素
/catalog/cd[price=10.90]/price

選擇一個以上的路徑
使用Or運算元(|)就可以選擇一個以上的路徑。例如:
/catalog/cd/title | catalog/cd/artist
選擇所有title以及artist元素
//title | //artist
選擇所有title以及artist以及price元素
//title | //artist | //price
選擇屬性
XPath中,除了選擇元素以外,也可以選擇屬性。屬性都是以@開頭。例如選擇檔中所有叫做country的屬性: //@country
選擇所有含有country這個屬性的cd元素: //cd[@country]
以下語法選擇出含有屬性的所有cd元素 //cd[@*]
以下語法選擇出country屬性值為UKcd元素 //cd[@country='UK']
其他

所有,且其Attribute是qty>3 或price>400 descendant::Item[@qty>3 or @price>400]"

只要掌握了xpath語法,理論上你就可以訪問xml檔中的任意節點和任意值

##HIDEME##