XML dan XPath

什么是 XPath?

XPath 是 XSLT 标準中的一個主要元素。

XPath 可用於定位(導航)XML 文件中的元素和屬性。

XPath

XPath
  • XPath 是用於定義 XML 文件各部分的語法
  • XPath 使用路徑表達式在 XML 文件中導航
  • XPath 包含標準函數庫
  • XPath 是 XSLT 和 XQuery 中的主要元素
  • XPath 是 W3C 推薦標準

XPath 路徑表達式

XPath 使用路徑表達式來選擇 XML 文件中的節點或節點集。這些路徑表達式看起來非常類似於您在使用傳統計算機文件系統時看到的表達式。

XPath 表達式可用於 JavaScript、Java、XML Schema、PHP、Python、C 和 C++ 以及許多其他語言。

XPath 用於 XSLT

XPath 是 XSLT 标準中的一個主要元素。

理解了 XPath,您就能充分利用 XSL。

Contoh XPath

我們將使用下面的 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="美食">
  <title lang="zh">雅舍谈吃</title>
  <author>梁实秋</author>
  <year>2013</year>
  <price>35</price>
</book>
<book category="儿童">
  <title lang="zh">了不起的狐狸爸爸</title>
  <author>罗尔德·达尔</author>
  <year>2009</year>
  <price>10.00</price>
</book>
<book category="文学">
  <title lang="zh">将熟悉变为陌生</title>
  <author>齐格蒙·鲍曼</author>
  <author>彼得·哈夫纳</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>
<book category="政治">
  <title lang="zh">论美国的民主</title>
  <author>托克维尔</author>
  <year>1989</year>
  <price>60.00</price>
</book>
</bookstore>

Di tabel di bawah ini, kami daftar beberapa ekspresi XPath serta hasil ekspresi tersebut:

Ekspresi XPath Hasil
/bookstore/book[1] Pilih elemen book yang menjadi anak elemen bookstore pertama.
/bookstore/book[last()] Pilih elemen book yang menjadi anak elemen bookstore terakhir.
/bookstore/book[last()-1] Pilih elemen book yang menjadi anak elemen bookstore ke-terakhir sebelum terakhir.
/bookstore/book[position()<3] Pilih dua elemen pertama book yang menjadi anak elemen bookstore.
//title[@lang] Pilih semua elemen title yang memiliki atribut bernama lang.
//title[@lang='en'] Pilih semua elemen title yang memiliki atribut "lang" dengan nilai "en".
/bookstore/book[price>35.00] Pilih semua elemen book di dalam elemen bookstore yang nilai elemen price melebihi 35.00.
/bookstore/book[price>35.00]/title 选择 bookstore 元素的 book 元素中,price 元素值大于 35.00 的所有 title 元素。

XPath 教程

您将在我们的 XPath 教程中学到有关 XPath 的更多知识。