Contoh XQuery

在本节,让我们通过研究一个例子来学习一些基础的 XQuery 语法。

XML 实例文档

我们将在下面的例子中使用这个 XML 文档。

"books.xml" :

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<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>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</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>

在您的浏览器中查看 "books.xml" 文件

如何从 "books.xml" 选取节点?

函数

XQuery 使用函数来提取 XML 文档中的数据。

doc() 用于打开 "books.xml" 文件:

doc("books.xml")

路径表达式

XQuery 使用路径表达式在 XML 文档中通过元素进行导航。

下面的路径表达式用于在 "books.xml" 文件中选取所有的 title 元素:

doc("books.xml")/bookstore/book/title

(/bookstore 选取 bookstore 元素,/book 选取 bookstore 元素下的所有 book 元素,而 /title 选取每个 book 元素下的所有 title 元素)

XQuery di atas boleh mengambil data di bawah ini:

<title lang="en">Everyday Italian</title>
<title lang="en">Harry Potter</title>
<title lang="en">XQuery Kick Start</title>
<title lang="en">Learning XML</title>

Kalimat

XQuery menggunakan kalimat untuk membatasi data yang diambil dari dokumen XML.

Kalimat berikut digunakan untuk memilih semua elemen book di dalam elemen bookstore, dan nilai elemen price di dalam elemen book mesti kurang daripada 30:

doc("books.xml")/bookstore/book[price<30]

XQuery di atas boleh mengambil data di bawah ini:

<book category="CHILDREN">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>