XQuery 語法
What is XQuery?
什么是XQuery?
- XQuery is the language for querying XML data
XQuery是查詢XML數據的語言 - XQuery for XML is like SQL for databases
XQuery與XML的關系類似于SQL與數據庫的關系 - XQuery is built on XPath expressions
XQuery 是建立在XPath表達式基礎上的 - XQuery is defined by the W3C
XQuery是由W3C 定義的 - XQuery is supported by all the major database engines (IBM, Oracle, Microsoft, etc.)
所有重要的數據庫引擎(如:IBM、Oracle、Microsoft,等等)都支持XQuery - XQuery will become a W3C standard - and developers can be sure that the code will work among different products
XQuery將會成為W3C的標準 —— 開發者都確信代碼可以在不同的產品之間運行
XQuery is About Querying XML
XQuery 是用于查詢XML的
XQuery is a language for finding and extracting elements and attributes from XML documents.
XQuery是用于從XML文檔中查找和提取元素和屬性的語言。
Here is an example of a question that XQuery could solve:
下面是一個關于XQuery所能解決的問題的案例:
"Select all CD records with a price less than $10 from the CD collection stored in the XML document called cd_catalog.xml".
從存儲在名為 “cd_catalog.xml” 的XML文檔內的CD集中選擇所有價格低于10美元的CD唱片。
XQuery and XPath
XQuery 和 XPath
XQuery 1.0 and XPath 2.0 share the same data model and support the
same functions and operators. If you have already studied XPath you
will have no problems with understanding XQuery.
XQuery 1.0 和 XPath 2.0 具有相同的數據模型并支持相同的函數和操作符。如果你已經掌握了XPath的相關知識,那么,理解XQuery就不成問題了。
You can read more about XPath in our XPath Tutorial.
你可以 在我們的XPath 教程中學習更多關于XPath的知識。
XQuery - Examples of Use
XQuery —— 使用案例
XQuery can be used to:
XQuery 可用于下述操作:
- Extract information to use in a Web Service
獲取在Web服務中使用的信息 - Generate summary reports
產生綜合報告。 - Transform XML data to XHTML
把XML數據轉換成XHTML形式 - Search Web documents for relevant information
在Web文檔中搜索相關信息
XQuery is Not (Yet) a Web Standard
XQuery 并不是網絡標準
XQuery is compatible with several W3C standards, such as XML, Namespaces, XSLT, XPath, and XML Schema.
XQuery和一些W3C的標準是相互吻合的,例如:XML、Namespaces [命名空間]、XSLT、XPath 和 XML Schema。
However, XQuery 1.0 is not yet a W3C Recommendation (XQuery is a
Working Draft). Hopefully it will be a recommendation in the near
future.
然而,XQuery 1.0 并不是W3C的推薦標準(XQuery 僅是一份工作草案)。相信在不久的將來,它會變成 W3C 推薦的標準吧。
Let's try to learn some basic XQuery syntax by looking at an example.
讓我們通過下面這個案例來學習一些關于XQuery 的基本語法。
The XML Example Document
XML 案例文檔
We will use the following XML document in the examples below.
我們將在下面的案例中使用“books.xml”文檔:
"books.xml":
“books.xml”文件內容如下:
<?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <book category="COOKING"> <book category="CHILDREN"> <book category="WEB"> <book category="WEB"> </bookstore> |
View the "books.xml" file in your browser.
在瀏覽器中瀏覽“books.xml”文件。
How to Select Nodes From "books.xml"?
如何從"books.xml"文件中選擇節點?
Functions
函數
XQuery uses functions to extract data from XML documents.
XQuery 使用函數從XML文檔中獲取數據。
The doc() function is used to open the "books.xml" file:
doc() 函數用于打開"books.xml"文件:
doc("books.xml") |
Path Expressions
路徑表達式
XQuery uses path expressions to navigate through elements in an XML document.
XQuery 通過路徑表達式操作XML文檔中的元素。
The following path expression is used to select all the title elements in the "books.xml" file:
下述路徑表達式用于在"books.xml"文件中選擇 title 元素:
doc("books.xml")/bookstore/book/title
|
(/bookstore selects the bookstore element, /book selects all the
book elements under the bookstore element, and /title selects all the
title elements under each book element)
(/bookstore 選擇 bookstore元素;/book 選擇 bookstore 元素下的所有 book 元素;/title 選擇每個book 元素下的所有title元素。
The XQuery above will extract the following:
上述的XQuery會獲取下述內容:
<title lang="en">Everyday Italian</title> |
Predicates
條件謂語項
XQuery uses predicates to limit the extracted data from XML documents.
XQuery 使用條件謂語項給從XML文件中摘取的數據附加一個條件。
The following predicate is used to select all the book elements
under the bookstore element that have a price element with a value that
is less than 30:
下面的條件謂語項是用來選擇 bookstore 元素下 price 元素值小于30的所有 book 元素的表達式:
doc("books.xml")/bookstore/book[price<30]
|
The XQuery above will extract the following:
上述XQuery語句會獲取下面的內容:
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
The XML Example Document
XML 案例文檔
We will use the "books.xml" document in the examples below (same XML file as in the previous chapter).
下述案例中,我們會用到 "books.xml" 文檔(上一章使用的XML文件)。
View the "books.xml" file in your browser.
在你的瀏覽器中瀏覽“books.xml”。
How to Select Nodes From "books.xml" With FLWOR
怎樣使用FLWOR表達式從"books.xml"文件中選擇節點
Look at the following path expression:
先看看下面的路徑表達式:
doc("books.xml")/bookstore/book[price>30]/title |
The expression above will select all the title elements under the
book elements that are under the bookstore element that have a price
element with a value that is higher than 30.
上述表達式將選擇 bookstore 元素下的 book 元素下的所有price 元素值大于30的 title 元素。
The following FLWOR expression will select exactly the same as the path expression above:
下述FLWOR表達式和上述路徑表達式選擇的值相同:
for $x in doc("books.xml")/bookstore/book |
The result will be:
結果如下:
<title lang="en">XQuery Kick Start</title> |
With FLWOR you can sort the result:
你可以使用FLWOR對結果進行分類排序:
for $x in doc("books.xml")/bookstore/book |
FLWOR is an acronym for "For, Let, Where, Order by, Return".
FLWOR是 "For、Let、Where、Order by、Return" 的首字母縮寫。
The for clause selects all book elements under the bookstore element into a variable called $x.
For子句把 bookstore 元素中的所有 book 元素發送到名為 $x 的變量內。
The where clause selects only book elements with a price element with a value greater than 30.
Where 子句僅選擇price元素值高于30的book元素。
The order by clause defines the sort-order. Will be sort by the title element.
order by 子句定義了“ 分類命令 ”。根據 title 元素進行分類。
The return clause specifies what should be returned. Here it returns the title elements.
Return 子句指定了返回的數據。這里返回的是 title 元素。
The result of the XQuery expression above will be:
上述 XQuery 表達式的結果如下:
<title lang="en">XQuery Kick Start</title>
The XML Example Document
XML 案例文檔
We will use the "books.xml" document in the examples below (same XML file as in the previous chapters).
下述案例中,我們會用到 "books.xml" 文檔(上一章使用的XML文件)。
View the "books.xml" file in your browser.
在你的瀏覽器中瀏覽“books.xml”。
Present the Result In an HTML List
在HTML列表中顯示結果
Look at the following XQuery FLWOR expression:
先看看下面的Query FLWOR表達式:
for $x in doc("books.xml")/bookstore/book/title |
The expression above will select all the title elements under the
book elements that are under the bookstore element, and return the
title elements in alphabetical order.
上述表達式會選擇在 bookstore 元素下的 book 元素下所有 title 元素,并按字母順序排列 title 元素后輸出。
Now we want to list all the book-titles in our bookstore in an HTML
list. We add <ul> and <li> tags to the FLWOR expression:
現在,我們希望在 HTML列表中列出 bookstore 的所有book-titles元素,因此,我們需要在 FLWOR 表達式中加入<ul>和<li>標簽:
<ul> |
The result of the above will be:
上述的結果顯示如下:
<ul> |
Now we want to eliminate the title element, and show only the data inside the title element:
現在,我們要除去 title 元素,只顯示 title 元素里的數據:
<ul> |
The result will be (an HTML list):
結果(一份HTML列表)顯示如下:
<ul>
<li>Everyday Italian</li>
<li>Harry Potter</li>
<li>Learning XML</li>
<li>XQuery Kick Start</li>
</ul>
In XQuery, there are seven kinds of nodes: element,
attribute, text, namespace, processing-instruction, comment, and
document (root) nodes.
在XQuery中,有7中不同的節點:元素、屬性、文本、命名空間、處理指令、注釋、文檔(根目錄)節點。
XQuery 術語
Nodes
節點
In XQuery, there are seven kinds of nodes: element, attribute, text,
namespace, processing-instruction, comment, and document (root) nodes.
XML documents are treated as trees of nodes. The root of the tree is
called the document node (or root node).
在XQuery里,有7中不同的節點:元素、屬性、文本、命名空間、處理指令、注釋、文檔(根目錄)節點,XML文檔是節點樹狀結構。“樹根”稱作文檔節點(或根節點)。
Look at the following XML document:
先看看下面這個XML文檔:
<?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <book> </bookstore> |
Example of nodes in the XML document above:
上述XML文檔中的節點案例:
<bookstore> (document node) <author>J K. Rowling</author> (element node) lang="en" (attribute node) |
Atomic values
“原子值”屬性值
Atomic values are nodes with no children or parent.
“原子值”屬性值只沒有子節點和父節點。
Example of atomic values:
“原子值”屬性值案例:
J K. Rowling "en" |
Items
項
Items are atomic values or nodes.
“項”是指原子值或節點。
Relationship of Nodes
節點間關系
Parent
父類
Each element and attribute has one parent.
每個元素和屬性都包含一個“父類”。
In the following example; the book element is the parent of the title, author, year, and price:
在下述案例中:book元素是title、author、year 和 price 元素的父類元素:
<book> |
Children
子類元素
Element nodes may have zero, one or more children.
元素節點可以包含任意個數的子類元素。
In the following example; the title, author, year, and price elements are all children of the book element:
在下述案例中,title、author、year 和 price元素都是book元素的子元素:
<book> |
Siblings
同類元素
Nodes that have the same parent.
擁有相同的父類元素的節點稱為同類元素。
In the following example; the title, author, year, and price elements are all siblings:
在下述案例中,title、author、year 和 price 元素都是“同類元素”:
<book> |
Ancestors
祖類元素
A node's parent, parent's parent, etc.
一個節點的父類元素,父類元素的父類元素,以此類推,稱為該節點的祖類元素。
In the following example; the ancestors of the title element are the book element and the bookstore element:
在下述案例中,title元素的 “祖類元素” 是 book 元素和 bookstore 元素。
<bookstore> <book> </bookstore> |
Descendants
孫類元素
A node's children, children's children, etc.
一個節點的子類元素,子類元素的子類元素,以此類推,稱為孫類元素。
In the following example; descendants of the bookstore element are the book, title, author, year, and price elements:
在下述案例中,bookstore 元素的孫類元素是book、title、author、year 和 price 元素:
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book> </bookstore>
XQuery is case-sensitive and XQuery elements, attributes, and variables must be valid XML names.
Xquery 區分字母大小寫,它的元素、屬性、變量必須是有效的XML名稱。
XQuery Basic Syntax Rules
XQuery 的基本語法規則
Some basic syntax rules:
一些基本語法規則:
- XQuery is case-sensitive
XQuery 區分字母大小寫 - XQuery elements, attributes, and variables must be valid XML names
它的元素、屬性、變量必須是有效的XML名稱 - An XQuery string value can be in single or double quotes
一個 XQuery 字符串值可以寫在單引號里或雙引號里 - An XQuery variable is defined with a $ followed by a name, e.g. $bookstore
一個 XQuery 變量定義是在“$”的符號后面跟上名稱等,例如:$bookstore - XQuery comments are delimited by (: and :), e.g. (: XQuery Comment :)
XQuery 注釋使用 “(: ”和“ :)” 進行分界,例如 (: XQuery Comment :)
XQuery Conditional Expressions
XQuery 的條件表達式
"If-Then-Else" expressions are allowed in XQuery.
XQuery 允許使用 "If-Then-Else" 條件表達式。
Look at the following example:
先看看下面的案例:
for $x in doc("books.xml")/bookstore/book |
Notes on the "if-then-else" syntax: parentheses around the if expression are required. else is required, but it can be just else ().
使用“if-then-else"條件語句時應注意的語法點:if 表達式允許出現圓括號;另外,如果使用了“if”,就必須使用“else”,也可以是else()。
The result of the example above will be:
上述案例輸出的結果如下:
<adult>Everyday Italian</adult> |
XQuery Comparisons
XQuery 比較
In XQuery there are two ways of comparing values.
XQuery 有兩種比較值的方法。
1. General comparisons: =, !=, <, <=, >, >=
常規比較符號:= 、 != 、 < 、 <= 、 > 、 >=
2. Value comparisons: eq, ne, lt, le, gt, ge
值的比較:eq 、 ne 、 lt 、 le 、 gt 、 ge
The difference between the two comparison methods are shown below.
下面列舉了兩種比較方法的不同之處。
Look at the following XQuery expressions:
先看看下面的XQuery表達式:
$bookstore//book/@q > 10
The expression above returns true if any q attributes
have values greater than 10.
如果所有上述q的屬性值大于10,那么,表達式將返回“true”(真)
$bookstore//book/@q gt 10
The expression above returns true if there is only one
q attribute returned by the expression, and its value
is greater than 10. If more than one q is returned,
an error occurs.
如果表達式返回的q屬性中,只有一個q值大于10,那么,上述表達式才返回“true”(真);否則
The XML Example Document
XML 案例文檔
We will use the "books.xml" document in the examples below (same XML file as in the previous chapters).
下述案例中,我們會用到 "books.xml" 文檔(上一章使用的XML文件)。
View the "books.xml" file in your browser.
在你的瀏覽器中瀏覽“books.xml”。
Adding Elements and Attributes to the Result
向結果中添加元素和屬性
As we have seen in a previous chapter, we may include elements and
attributes from the input document ("books.xml) in the result:
就像在前幾章中所看到的,我們可以把來自輸入文檔("books.xml)的元素和屬性添加到結果中:
for $x in doc("books.xml")/bookstore/book/title |
The XQuery expression above will include both the title element and the lang attribute in the result, like this:
上述 XQuery 表達式會將 title 元素和 lang 屬性添加到結果中,如下所示:
<title lang="en">Everyday Italian</title> |
The XQuery expression above returns the title elements the exact same way as they are described in the input document.
上述 XQuery 表達式獲取了 title 元素,它們和原來在輸入文檔中被描述的一樣。
We now want to add our own elements and attributes to the result!
現在,我們希望把我們自己的元素和屬性添加到結果中。
Add HTML Elements and Text
添加 HTML 元素和文本
Now, we want to add some HTML elements to the result. We will put the result in an HTML list - together with some text:
現在,我們希望將一些HTML元素添加到結果中。我們將把結果連同一些文本內容放在一個HTML列表中:
<html> <h1>Bookstore</h1> <ul> </body> |
The XQuery expression above will generate the following result:
上述XQuery表達式將會輸出下面的結果:
<html> <h1>Bookstore</h1> <ul> </body> |
Add Attributes to HTML Elements
向HTML元素中添加屬性
Next, we want to use the category attribute as a class attribute in the HTML list:
接下來,我們希望把 category 屬性作為 HTML 列表的一個類屬性:
<html> <h1>Bookstore</h1> <ul> </body> |
The XQuery expression above will generate the following result:
上述XQuery表達式將會輸出下面的結果:
<body> <h1>Bookstore</h1> <ul>
<li class="COOKING">Everyday Italian</li>
<li class="CHILDREN">Harry Potter</li>
<li class="WEB">Learning XML</li>
<li class="WEB">XQuery Kick Start</li>
</ul> </body>
</html>
Selecting and Filtering Elements
選擇和過濾元素
As we have seen in the previous chapters, we are selecting and
filtering elements with either a Path expression or with a FLWOR
expression.
如同在前幾章里所看到的那樣,我們使用路徑表達式或FLWOR表達式來選擇和過濾元素。
Look at the following FLWOR expression:
先看看下面的FLWOR表達式:
for $x in doc("books.xml")/bookstore/book |
- for - (optional) binds a variable to each item returned by the in expression
for -(可選的)給從 “in 表達式” 內返回每一個項綁定一個變量 - let - (optional)
let -(可選的) - where - (optional) specifies a criteria
where -(可選的)指定了一個標準 - order by - (optional) specifies the sort-order of the result
order by - (可選的)指定了結果的排列次序 - return - specifies what to return in the result
return - 指定了在結果中返回的內容
The for Clause
For 子句
The for clause binds a variable to each item returned by the in
expression. The for clause results in iteration. There can be multiple
for clauses in the same FLWOR expression.
給從 “in 表達式” 中返回每一個項綁定一個變量。For子句會導致重復。在相同的FLWOR表達式中,可以包含多個for子句。
To loop a specific number of times in a for clause, you may use the to keyword:
在for子句中對一個指定的數字進行多次循環,你可以使用關鍵詞 “ to ”:
for $x in (1 to 5) |
Result:
結果:
<test>1</test> |
The at keyword can be used to count the iteration:
關鍵字 “at” 可用于計算重復次數:
for $x at $i in doc("books.xml")/bookstore/book/title |
Result:
結果如下:
<book>1. Everyday Italian</book> |
It is also allowed with more than one in expression in the for clause. Use comma to separate each in expression:
在for子句中,允許出現一項或多項 “in 表達式”;使用逗號將表達式中的每項分開:
XQuery 1.0, XPath 2.0, and XSLT 2.0 share the same functions library.
XQuery 1.0、XPath 2.0 和 XSLT 2.0 包含相同的函數庫。
XQuery Functions
XQuery 函數
XQuery includes over 100 built-in functions. There are functions for
string values, numeric values, date and time comparison, node and QName
manipulation, sequence manipulation, Boolean values, and more. You can
also define your own functions in XQuery.
XQuery 包括超過100個內置函數,具體如下:字符串值、數值、日期時間值、節點以及QName操作、排序操作、邏輯值等函數。你也可以在XQuery內定義自己的函數。
XQuery Built-in Functions
XQuery 內置函數
The URI of the XQuery function namespace is:
http://www.w3.org/2005/02/xpath-functions
XQuery函數名稱空間(namespaces)的URI是:
http://www.w3.org/2005/02/xpath-functions
The default prefix for the function namespace is fn:.
默認的函數命名空間前綴是fn:.
Tip: Functions are often called with the fn:
prefix, such as fn:string(). However, since fn: is the default prefix
of the namespace, the function names do not need to be prefixed when
called.
提示:函數常常以“fn:”為前綴名調用,例如fn:string();然而,因為fn:是命名空間的默認前綴,所以這個函數的名稱并不需要通過前綴名來調用。
The reference of all the built-in XQuery 1.0 functions is located in our XPath tutorial.
XQuery 1.0內置函數參考。
Examples of Function Calls
函數調用實例
A call to a function can appear where an expression may appear. Look at the examples below:
函數調用可以出現在一個表達式中所有可能出現的地方,看下面的案例:
Example 1: In an element
例1:在一個元素中:
<name>{uppercase($booktitle)}</name> |
Example 2: In the predicate of a path expression
例2:在路徑表達的條件謂語項中:
doc("books.xml")/bookstore/book[substring(title,1,5)='Harry'] |
Example 3: In a let clause
例3:在let子句中:
let $name := (substring($booktitle,1,4)) |
XQuery User-Defined Functions
XQuery 用戶自定義函數
If you cannot find the XQuery function you need, you can write your own.
如果你找不到需要使用的XQuery函數,你可以自己書寫。
User-defined functions can be defined in the query or in a separate library.
用戶自定義函數可以在查詢語句或獨立庫中進行定義。
Syntax
語法
declare function prefix:function_name($parameter AS datatype) (: ...function code here... :) }; |
Notes on user-defined functions:
用戶自定義函數需要注意以下幾點:
- Use the declare function keyword
使用 “declare function(函數聲明)” 關鍵詞 - The name of the function must be prefixed
函數名稱要必須包含前綴 - The data type of the parameters are mostly the same as the data types defined in XML Schema
參數的數據類型要和在XML Schema中定義的數據類型基本一致 - The body of the function must be surrounded by curly braces
函數的主體部分必須在圓括號內書寫
Example of a User-defined Function Declared in the Query
在查詢語句里聲明的用戶自定義函數案例
declare function local:minPrice($price as xs:decimal?,
$discount as xs:decimal?)
AS xs:decimal?
{
let $disc := ($price * $discount) div 100
return ($price - $disc)
}; (: Below is an example of how to call the function above :) <minPrice>{local:minPrice($book/price, $book/discount)}</minPrice>
XQuery Summary
XQuery 概要
This tutorial has taught you how to query XML data.
這篇教程將教你如何查詢XML數據。
You have learned that XQuery was designed to query anything that can appear as XML, including databases.
你應該已經了解:XQuery是用于查詢包括數據庫在內的以XML形式出現的任何內容。
You have also learned how to query the XML data with FLWOR
expressions, and how to construct XHTML output from the collected data.
你應該已經了解怎樣使用FLWOR表達式查詢XML數據,以及怎樣從已選數據里構建XHTML結果。
For more information on XQuery, please look at our XQuery Reference.
在我們的XQuery 參考上有關于XQuery的更多內容。
Now You Know XQuery, What's Next?
學會了XQuery,接下來該學些什么呢?
The next step is to learn about XLink and XPointer.
下一步是學習與 XLink 和 XPointer 相關的內容。
XLink and XPointer
Linking in XML is divided into two parts: XLink and XPointer.
XML中的鏈接分為兩個部分:XLink 和XPointer。
XLink and XPointer define a standard way of creating hyperlinks in XML documents.
XLink 和 XPointer 定義了在XML文檔里創建超鏈接的標準。
If you want to learn more about XLink and XPointer, please visit our XLink and XPointer tutorial.
在我們的XLink / XPointer教程中,你可以學習與 XLink 和 XPointer 相關的更多內容。
XQuery 1.0 and XPath 2.0 share the same data model and support the same functions and operators.
XQuery 1.0 和 XPath 2.0擁有同樣的數據模式并支持相同的函數和操作。
XQuery Functions
XQuery函數
XQuery is built on XPath expressions. XQuery 1.0 and XPath 2.0 share
the same data model and support the same functions and operators.
XQuery 是建立在 XPath 表達式的基礎上的。XQuery 1.0 和 XPath 2.0 包含相同的數據模型并支持相同的函數和操作符。
XPath Operators
XPath 操作符
XPath Functions
XPath 函數
XQuery Data Types
XQuery 數據類型
XQuery shares the same data types as XML Schema 1.0 (XSD).
XQuery 和 XML Schema 1.0 (XSD) 包含了相同的數據類型。
XSD String
XSD 字符串
XSD Date
XSD 日期
XSD Numeric
XSD 數字
XSD Misc
XSD 混合數據類型