XQuery 教程

XQuery 教程(2025最新版)

XQuery 是专为查询 XML 数据设计的强大查询语言,由 W3C 制定,最新稳定版本是 XQuery 3.1(2017年发布)。它类似于 SQL 之于关系型数据库,XQuery 之于 XML/原生 XML 数据库(如 BaseX、eXist-db、MarkLogic、Saxon)。

1. 基本概念

概念说明
FLWORFor-Let-Where-Order by-Return,XQuery 最核心的语句(类似 SQL 的 SELECT)
XPathXQuery 内置 XPath 3.1,用于定位节点
序列 (Sequence)XQuery 基本数据类型,一切都是序列(可包含节点、原子值)
函数式语言纯函数式、无副作用、支持高阶函数(函数作为参数)

2. 环境准备(推荐三种方式)

  1. 在线运行(最快)
  • https://www.w3schools.com/xml/xquery_example.asp
  • https://basex.org/products/online-editor/
  • https://xqueryinstitute.com/(支持 XQuery 3.1)
  1. 本地安装 BaseX(推荐学习用)
    下载:https://basex.org/download/
    启动 GUI → New → 粘贴代码 → Execute (F7)
  2. 氧士 XML Editor (Oxygen XML Editor)Saxon-HE(Java命令行)

3. 第一个例子

准备一个 XML 文件 books.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

简单查询所有书名

for $book in doc("books.xml")/bookstore/book
return $book/title

结果:

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

FLWOR 经典写法(等价于 SQL)

for $book in doc("books.xml")/bookstore/book
where $book/price > 30
order by $book/price descending
return 
  <expensive-book>{
    $book/title,
    $book/price
  }</expensive-book>

结果:

<expensive-book>
  <title lang="en">Learning XML</title>
  <price>39.95</price>
</expensive-book>

4. FLWOR 语句详解

for    $x in 表达式      (: 迭代 :)
let    $y := 表达式      (: 绑定变量,不迭代 :)
where  条件              (: 过滤 :)
order by 表达式 descending/ascending
return 表达式            (: 构造结果 :)

let 示例(分组统计常用)

let $books := doc("books.xml")/bookstore/book
let $avg := avg($books/price)
return <average-price>{ $avg }</average-price>

5. 常用函数一览(XQuery 3.1)

类别函数示例
节点函数doc(), collection(), root(), path(), node-name()
字符串contains(), starts-with(), substring(), upper-case()
数值avg(), sum(), count(), round(), ceiling()
序列distinct-values(), index-of(), insert-before()
日期current-date(), year-from-date()
高阶函数filter(), fold-left(), map()
JSON 支持json-doc(), parse-json(), serialize(…, map{‘method’:’json’})

6. XQuery 与 JSON(3.1 新特性)

let $json := parse-json('{"name":"John", "age":31, "city":"New York"}')
return $json?name
(: 返回 "John" :)

序列化成 JSON:

serialize(<person name="Mary"><age>25</age></person>, 
          map { 'method': 'json' })

7. 条件表达式(if-then-else)

for $book in doc("books.xml")/bookstore/book
return
  <book>{
    $book/title,
    if ($book/price > 30) 
    then <status>expensive</status>
    else <status>affordable</status>
  }</book>

8. 常用 XPath 轴(axis)

含义
child::子节点(默认)
descendant::所有后代
descendant-or-self::包括自己
parent::父节点
ancestor::所有祖先
following-sibling::同级后面的兄弟
preceding-sibling::同级前面的兄弟
attribute:: 或 @属性

示例:查找所有 2005 年出版的书的作者

doc("books.xml")//book[year=2005]/author

9. 更新(XQuery Update Facility 3.0,仅部分数据库支持)

copy $tmp := doc("books.xml")
modify (
  replace value of node $tmp//book[title="Harry Potter"]/price with 39.99
)
return $tmp

支持的数据库:BaseX、eXist-db、MarkLogic

10. 实战案例

1. 分组统计(类似 SQL GROUP BY)

for $cat in distinct-values(doc("books.xml")//book/@category)
let $books := doc("books.xml")//book[@category = $cat]
return
  <category name="{$cat}">
    <count>{count($books)}</count>
    <avg-price>{avg($books/price)}</avg-price>
  </category>

2. 连接两个 XML(join)

for $book in doc("books.xml")//book,
    $review in doc("reviews.xml")//review[book-id = $book/@id]
return
  <book-with-review>{
    $book/title,
    $review/rating
  }</book-with-review>

学习资源推荐(2025)

  1. 官方规范(带完整函数库)
    https://www.w3.org/TR/xquery-31/
  2. 在线练习(最友好)
    https://www.xqueryinstitute.com/
  3. BaseX 官方教程(带 GUI)
    https://docs.basex.org/wiki/XQuery_Tutorial
  4. 书籍(经典)
    《XQuery 2nd Edition》 Priscilla Walmsley(2015,涵盖 3.1)
  5. 中文资源
  • 掘金小册《XML 与 XQuery 实战》
  • 知乎专栏 “XQuery 从入门到精通”

现在就打开 BaseX 或在线编辑器,把上面的例子一个个敲一遍,你就能快速上手 XQuery 了!有任何具体问题欢迎继续提问~

文章已创建 2783

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部