2012年3月28日 星期三

XML Path Language (XPath)

為什麼要使用XPath呢? 其實對於一份XML文件而言, 他的結構如同我們在檔案系統裡面所看到的結構, 雖不同, 但亦不遠矣, 所以就有很聰明的人想到, 那能不能像目錄結構一樣的來查詢或是訪問這些存在XML裡的資料呢? 答案當然是可行的…
例如, 我們有這樣子的XML:
<?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>
在XPath中定義的語法如下:
選擇節點:
Expression Description
nodename Selects all child nodes of the named node
/ Selects from the root node
// Selects nodes in the document from the current node that match the selection no matter where they are
. Selects the current node
.. Selects the parent of the current node
@ Selects attributes
那我們就可以使用bookstore選到所有下面的子節點, 使用/bookstore亦同, 但是是由根節點開始找。bookstore/book, 就能選到所有book節點。
//book可以選到bookstore下所有的book節點, 和bookstore/book有點不太一樣。//@lang, 當然這裡選到的就是所有的attribute了。
不過光是選到哪個element或節點, 以及哪個attribute並不能當成查詢來使用, 查詢的目的在於能做一些運算, 像是>, <, =之類的才有辦法, 另外也要有and, or這樣子的關係表示句才可以, 在XPath這種查詢語言裡當然也有囉。
/bookstore/book[1], 查詢第一筆book, XPath並沒有下義第0筆這樣的東西, 從1開始, 但MS IE 5是從0開始, 我猜是他們的RD沒有讀懂XPath。
/bookstore/book[last()], 查最後一筆
/bookstore/book[last()], 查最倒數第二筆, 但要注意, XPath沒有下義first(), 因為第一筆就是[1]了
/bookstore/book[position()<3], Selects the first two book elements that are children of the bookstore element
//title[@lang='eng'], 查詢所有attribute為lan==’eng’
/bookstore/book[price>35.00], 這就很簡單了, price > 35.00
/bookstore/book[price>35.00]/title, 選price > 35.00下所有的title節點
當然在選節點時我們有可能遇到不知道那是什麼名稱的節點, XPath也提供了”* ”
所以可以這樣子下:
/bookstore/*
//*
//title[@*]
大至上語法的使用就像這樣, 但至於哪些地方用得到呢? 我本人是在使用EvtSubscribe來查詢windows event log時遇到XPath這東西, 要不然應該是一輩子都不會知道這樣子的東西存在於人世間。
http://msdn.microsoft.com/en-us/library/windows/desktop/aa385487(v=vs.85).aspx

沒有留言: