EvoTalk

12 十月, 2009

XPath

Posted by: asd In: Web| 程式設計 ()

xml data

CODE:
  1. <?xml version="1.0" encoding="ISO-8859-1"?>
  2. <catalog>
  3.   <cd country="USA">
  4.     <title>Empire Burlesque</title>
  5.     <artist>Bob Dylan</artist>
  6.     <price>10.90</price>
  7.   </cd>
  8.   <cd country="UK">
  9.     <title>Hide your heart</title>
  10.     <artist>Bonnie Tyler</artist>
  11.     <price>10.0</price>
  12.   </cd>
  13.   <cd country="USA">
  14.     <title>Greatest Hits</title>
  15.     <artist>Dolly Parton</artist>
  16.     <price>9.90</price>
  17.   </cd>
  18. </catalog>

XPath expressions

/catalog selects the root element
/catalog/cd selects all the cd elements of the catalog element
/catalog/cd/price selects all the price elements of all the cd elements of the catalog element
/catalog/cd[price>10.0] selects all the cd elements with price greater than 10.0
starts with a slash(/) represents an absolute path to an element
starts with two slashes(//) selects all elements that satisfy the criteria
//cd selects all cd elements in the document
/catalog/cd/title | /catalog/cd/artist selects all the title and artist elements of the cd elements of catalog
//title | //artist selects all the title and artist elements in the document
/catalog/cd/* selects all the child elements of all cd elements of the catalog element
/catalog/*/price selects all the price elements that are grandchildren of catalog
/*/*/price selects all price elements which have two ancestors
//* selects all elements in the document
/catalog/cd[1] selects the first cd child of catalog
/catalog/cd[last()] selects the last cd child of catalog
/catalog/cd[price] selects all the cd elements that have price
/catalog/cd[price=10.90] selects cd elements with the price of 10.90
/catalog/cd[price=10.90]/price selects all price elements with the price of 10.90
//@country selects all "country" attributes
//cd[@country] selects cd elements which have a "country" attribute
//cd[@*] selects cd elements which have any attribute
//cd[@country='UK'] selects cd elements with "country" attribute equal to 'UK'

reference:
Manipulate XML data with XPath and XmlDocument (C#)
XPath Tutorial

Most Commented Posts



No Responses to "XPath"

Comment Form


  • BK: 大於和小於在今日更廣泛地使用於標籤上,故在此補充該英文用法: : angle bracket []: square bracket
  • luh1688: 非常實用且謝謝!~
  • asd: 好的,不過很久沒修改了,不知道能不能動 寄到您的yahoo信箱
  • LIANG: nice post, thank you
  • Justmaker: 您好,請問可以跟你要source嗎?我最近有在看股票,想要enhance您的小工具,不知是否可以開放?

Category