การระบุเส้นทางด้วย XPath ทำได้สองแบบ
แบบแรกคือ absolute location เราระบุเส้นทางที่แน่นอนลงไปตรงๆ เช่น /bookstore/book/price
อีกวิธีคือ relative location ใช้ความสัมพันธ์มาระบุ เช่น bookstore/child::*/child::price
ซึ่งทั้งสองวิธีจะได้ price ออกมาเหมือนกัน
ข้อสังเกตคือ absolute location จะต้องขึ้นต้นด้วย / เพื่ออ้างอิงจุดเริ่มจาก root เสมอ
ส่วน relative location จะไม่ขึ้นต้นด้วย /
การเข้าถึง node ที่ต้องการด้วยวิธี absolute location
ใช้ XML ตัวนี้ประกอบการอธิบายนะคะ
โค้ด: เลือกทั้งหมด
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<a>
<stuff>HERE A1</stuff>
</a>
<a>
<stuff>HERE A2</stuff>
</a>
<a>
<b>
<c>HERE C</c>
</b>
</a>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
คำสั่งลือก node
-
ชื่อnode ใช้เลือกทุก node ที่มีชื่อตามที่ประกาศ เช่น bookstore
-
/ เริ่มเรียกเข้ามาจาก root (ใช้เข้าถึง element ลูก) เช่น /bookstore
-
// ใช้เข้าถึงทุก element ได้ในทุกะดับความลึก
เช่น //book คำสั่งนี้จะทำการเลือกทุกelementที่ชื่อว่า book โดยไม่สนใจระดับของข้อมูล
(//book จะให้ผลเหมือนกับ /bookstore/book)
-
. เลือก element ปัจจุบัน
-
.. เลือก parent node ของตัวเอง
-
@ ใช้เลือก attributes โดยวางไว้หน้าชื่อ attributes
-
* ใช้เลือกทุก element
-
@* เลือกทุกattributes
ตัวอย่าง
/bookstore/book
แบบนี้จะเป็นการเลือก element book ทั้งหมดที่เป็น child node ของ element bookstore
- a.jpg (131.9 KiB) Viewed 6210 times
//@lang
เลือกแอททริบิวต์ทุกตัวที่ชื่อว่า lang
- b.jpg (81.42 KiB) Viewed 6210 times
/bookstore/*
เลือกchild node ทุกตัวของbookstore
- c.jpg (120.98 KiB) Viewed 6210 times
//title[@*]
เลือกelement title ทุกตัวที่มี attributes
- d.jpg (142.63 KiB) Viewed 6210 times
นอกจากนี้เรายังสามารถระบุตำแหน่งหรือเพิ่มนิพจน์บูลีนเข้าไปได้ด้วย
เช่น
/bookstore/book[1]
จะเป็นการเลือก element book ที่เป็นchild node ลำดับแรกของ element bookstore
- f.jpg (136.04 KiB) Viewed 6210 times
/bookstore/book[position()<3]
จะเป็นการเลือก element book ที่เป็น child node สองลำดับแรกของ element bookstore
- g.jpg (139.19 KiB) Viewed 6210 times
//title[@lang]
เลือกทุก element ที่ชื่อ title และมี attributes ชื่อ lang
- h.jpg (154.29 KiB) Viewed 6210 times
/bookstore/book/title[@lang='en']
เลือกทุก element ที่ชื่อ title และมี attributes ชื่อ lang ที่มีค่าเท่ากับ en
- e.jpg (132.38 KiB) Viewed 6210 times
/bookstore/book[price>35.00]/title
เลือกทุก element ที่ชื่อ title ที่เป็น child node ของ element book ที่ element price มีค่ามากกว่า 35.00
- i.jpg (134.27 KiB) Viewed 6210 times