跳轉到內容

XQuery/使用 XQuery 函式

來自華夏公益教科書,一個開放的書籍專案

您想使用現有的 XQuery 函式。您需要能夠理解函式的工作原理以及它們是如何記錄的。

XQuery 1.0 規範包含許多用於處理字串、URI 和其他資料的內建函式。要使用內建函式,您需要知道它的輸入及其資料型別以及它建立的輸出形式。

理解 XQuery 引數和返回值型別

[編輯 | 編輯原始碼]

XQuery 是一種強型別語言,因此函式通常經過精心設計以使用一組受限的資料型別。當您使用引數將資料傳遞給函式時,您必須指定其型別,使用元素、節點、專案、序列或任何 XML 模式資料型別的組合。除了資料型別之外,還使用字尾稱為出現指示符,例如“+”、“?”或“*”,緊跟在資料型別之後,以指示引數是否可選或可以具有多個值。以下是三種出現指示符及其含義

  • ? 匹配零個或一個專案
  • * 匹配零個或多個專案
  • + 匹配一個或多個專案

應注意理解單個序列作為引數與重複的一組專案之間的區別。

XQuery 語言大約有 111 個內建函式,但許多人發現 10% 的 XQuery 函式被使用了 90% 的時間。以下是一些最常用的函式

 string-length($string as xs:string) as xs:integer - returns the length of a string as the number of its characters

示例:string-length("Hello") 返回 5,因為字串 "Hello" 長度為五個字元。

 concat($input as xs:anyAtomicType?) as xs:string - concatenates a list of strings together.

該函式不接受一組值,只接受作為單獨引數傳遞的單個原子值。

示例:concat('big', 'red', 'ball') 返回 "bigredball"

 string-join($sequence as xs:string*, $delimiter as xs:string) as xs:string - combines the items in a sequence, separating them with a delimiter

示例:string-join(('big', 'red', 'ball'), '-') 返回 "big-red-ball"

請注意,string-join 的第一個引數是單個專案序列,而 concat 的引數是零個或多個字串。

示例資料型別

[編輯 | 編輯原始碼]
  • xs:date 指的是名為 xs:date 的內建原子模式型別
  • attribute()? 指的是可選的屬性節點
  • element() 指的是任何元素節點
  • element(po:shipto, po:address) 指的是具有名稱 po:shipto 且具有型別註釋 po:address(或從 po:address 派生的模式型別)的元素節點
  • element(*, po:address) 指的是任何名稱的元素節點,其型別註釋為 po:address(或從 po:address 派生的型別)
  • element(customer) 指的是名為 customer 的元素節點,其型別註釋可以是任何
  • schema-element(customer) 指的是名稱為 customer(或在由 customer 領導的替換組中)的元素節點,其型別註釋與作用域內元素宣告中為 customer 元素宣告的模式型別匹配
  • node()* 指的是零個或多個任意型別的節點的序列
  • item()+ 指的是一個或多個節點或原子值的序列

返回結果

[編輯 | 編輯原始碼]

您編寫的每個 XQuery 函式都會返回一個結果。

在以下示例中,輸入是 0 到多個節點的序列,輸出是 0 到多個節點的序列

(: input 0 to many nodes and return 0 to many nodes :)
declare function local:myFunction($input as node()*) as node()* {

在以下示例中,輸入是單個必需節點,輸出是單個必需節點。

(: input a single required nodes and return a single required node :)
declare function local:myFunction($input as node()) as node() {

在以下示例中,輸入是單個可選節點,輸出是單個可選節點。

(: input a single optional nodes and return a single optional node :)
declare function local:myFunction($input as node()?) as node()? {

有用參考

[編輯 | 編輯原始碼]

有關 eXist 中所有可用函式(包括 XQuery 中未定義的函式)的權威文件,請參閱 eXist XQuery 函式文件

有關如何指定序列型別的詳細資訊,請參閱 XQuery 序列型別

有關標準 XQuery 和 XPath 函式庫,您還可以參考 XQuery 1.0 和 XPath 2.0 函式和運算子

另請參閱著名 XQuery 專家 Pricilla Walmsley 在 FunctX XQuery 函式庫 中的函式詳細文件和示例

華夏公益教科書