简体中文 繁體中文 English 日本語 Deutsch 한국 사람 بالعربية TÜRKÇE português คนไทย Français

站内搜索

搜索

活动公告

11-02 12:46
10-23 09:32
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,将及时处理!
10-23 09:31
10-23 09:28
通知:签到时间调整为每日4:00(东八区)
10-23 09:26

XQuery编程技巧实战宝典从入门到精通全面解析XML数据查询与处理的核心方法提升开发效率解决实际工作中的各类挑战助您成为专家

3万

主题

423

科技点

3万

积分

大区版主

木柜子打湿

积分
31916

三倍冰淇淋无人之境【一阶】财Doro小樱(小丑装)立华奏以外的星空【二阶】⑨的冰沙

发表于 2025-10-2 17:40:24 | 显示全部楼层 |阅读模式 [标记阅至此楼]

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

XQuery是一种用于查询和处理XML数据的强大语言,它已经成为XML数据处理领域的事实标准。随着XML在各种企业应用、Web服务和数据交换中的广泛应用,掌握XQuery技能对于开发人员来说变得越来越重要。本文将从基础概念开始,逐步深入到高级技巧和实战应用,帮助读者全面掌握XQuery编程,提升开发效率,解决实际工作中的各类挑战。

XQuery的设计目标是能够灵活地查询和转换XML数据,它结合了SQL的查询能力和XPath的导航能力,同时具备函数式编程语言的特性。无论是处理大型XML文档、进行数据转换,还是构建Web服务,XQuery都能提供高效、优雅的解决方案。

XQuery基础

XQuery简介

XQuery(XML Query)是一种由W3C开发的查询语言,专门用于从XML文档中提取和操作数据。它于2007年成为W3C推荐标准,目前最新版本是3.1版本。XQuery不仅可以查询XML数据,还可以对数据进行转换、构造新的XML结构,甚至可以与关系数据库、Web服务等其他数据源集成。

XQuery与XPath的关系

XQuery构建在XPath之上,XPath提供了在XML文档中定位节点的语法,而XQuery则扩展了这些功能,增加了数据查询、转换和构造的能力。简单来说,XPath是XQuery的一个子集,用于在XQuery表达式中定位XML节点。

XQuery数据模型

XQuery使用XDM(XQuery and XPath Data Model)数据模型,它将XML文档表示为一个有序的节点树。在这个模型中,有七种节点类型:

1. 文档节点(Document Node)
2. 元素节点(Element Node)
3. 属性节点(Attribute Node)
4. 文本节点(Text Node)
5. 命名空间节点(Namespace Node)
6. 处理指令节点(Processing Instruction Node)
7. 注释节点(Comment Node)

基本语法和表达式

XQuery的基本语法类似于SQL,但更加灵活。下面是一个简单的XQuery示例:
  1. (: 这是一个简单的XQuery示例 :)
  2. for $book in /bookstore/book
  3. where $book/price > 30
  4. return $book/title
复制代码

这个查询从bookstore中选择价格大于30的所有书籍的标题。

XQuery支持多种表达式类型:

1. 路径表达式:使用XPath语法定位节点
2. FLWOR表达式:XQuery的核心,用于复杂查询
3. 条件表达式:if-then-else
4. 量词表达式:some/every
5. 序列操作:处理节点序列

XQuery开发环境

要开始XQuery开发,你需要一个支持XQuery的环境。以下是一些流行的XQuery处理器:

1. BaseX:开源的XML数据库和XQuery处理器
2. eXist-db:开源的XML数据库
3. Saxon:高性能的XSLT和XQuery处理器
4. Oracle XML DB:Oracle数据库中的XQuery实现
5. SQL Server:Microsoft SQL Server中的XQuery支持

大多数现代IDE也提供XQuery支持,如oXygen XML Editor、XMLSpy等。

XQuery核心功能

基本查询操作

路径表达式是XQuery中最基本的查询方式,它使用XPath语法来定位XML文档中的节点。以下是一些示例:
  1. (: 选择所有书籍 :)
  2. /bookstore/book
  3. (: 选择第一本书 :)
  4. /bookstore/book[1]
  5. (: 选择价格大于30的书籍 :)
  6. /bookstore/book[price > 30]
  7. (: 选择所有书籍的标题 :)
  8. /bookstore/book/title
复制代码

XQuery中的序列是零个或多个项目的有序集合。序列操作是XQuery的重要组成部分:
  1. (: 创建序列 :)
  2. (1, 2, 3, 4, 5)
  3. (: 序列过滤 :)
  4. (1, 2, 3, 4, 5)[. > 3]  (: 结果: 4, 5 :)
  5. (: 序列排序 :)
  6. for $num in (3, 1, 4, 2)
  7. order by $num
  8. return $num  (: 结果: 1, 2, 3, 4 :)
复制代码

FLWOR表达式

FLWOR(For, Let, Where, Order by, Return)表达式是XQuery的核心,它提供了强大的查询和转换能力。FLWOR表达式类似于SQL中的SELECT-FROM-WHERE,但功能更加强大。
  1. (: 基本FLWOR示例 :)
  2. for $book in /bookstore/book
  3. where $book/price > 30
  4. order by $book/title
  5. return <book>{$book/title}</book>
复制代码

这个查询选择价格大于30的书籍,按标题排序,并返回包含标题的新book元素。

Let子句用于将值绑定到变量,可以在表达式中重复使用:
  1. (: 使用let子句计算折扣价 :)
  2. for $book in /bookstore/book
  3. let $discount := $book/price * 0.9
  4. where $book/price > 30
  5. return
  6.     <book>
  7.         {$book/title}
  8.         <originalPrice>{$book/price}</originalPrice>
  9.         <discountedPrice>{$discount}</discountedPrice>
  10.     </book>
复制代码

多个For子句可以用于处理多个序列或进行连接操作:
  1. (: 使用多个for子句连接书籍和作者 :)
  2. for $book in /bookstore/book
  3. for $author in /authors/author
  4. where $book/author_id = $author/@id
  5. return
  6.     <bookAuthor>
  7.         {$book/title}
  8.         {$author/name}
  9.     </bookAuthor>
复制代码

XQuery 3.0引入了Group By子句,用于分组操作:
  1. (: 按类别分组书籍并计算每类书籍的平均价格 :)
  2. for $book in /bookstore/book
  3. group by $category := $book/category
  4. return
  5.     <category name="{$category}">
  6.         <averagePrice>{avg($book/price)}</averagePrice>
  7.         <count>{count($book)}</count>
  8.     </category>
复制代码

条件表达式和量词

XQuery支持条件表达式,用于基于条件执行不同的操作:
  1. (: 根据价格添加折扣信息 :)
  2. for $book in /bookstore/book
  3. return
  4.     <book>
  5.         {$book/title}
  6.         {$book/price}
  7.         {
  8.             if ($book/price > 50) then <discount>20%</discount>
  9.             else if ($book/price > 30) then <discount>10%</discount>
  10.             else <discount>5%</discount>
  11.         }
  12.     </book>
复制代码

量词表达式用于检查序列中的元素是否满足特定条件:
  1. (: 检查是否有价格超过100的书籍 :)
  2. some $book in /bookstore/book satisfies $book/price > 100
  3. (: 检查所有书籍是否都有作者 :)
  4. every $book in /bookstore/book satisfies exists($book/author)
复制代码

节点构造和修改

XQuery可以构造新的XML节点:
  1. (: 构造新的book元素 :)
  2. <book category="fiction">
  3.     <title>新书籍</title>
  4.     <author>作者名</author>
  5.     <price currency="USD">29.99</price>
  6. </book>
  7. (: 使用计算构造器动态创建元素 :)
  8. element book {
  9.     attribute category {"fiction"},
  10.     element title {"新书籍"},
  11.     element author {"作者名"},
  12.     element price {
  13.         attribute currency {"USD"},
  14.         29.99
  15.     }
  16. }
复制代码

XQuery Update Facility提供了修改XML文档的功能:
  1. (: 插入新节点 :)
  2. insert node <review>优秀</review> into /bookstore/book[1]
  3. (: 删除节点 :)
  4. delete node /bookstore/book[price < 10]/price
  5. (: 替换节点 :)
  6. replace value of node /bookstore/book[1]/price with 39.99
  7. (: 重命名节点 :)
  8. rename node /bookstore/book[1]/title as "bookTitle"
复制代码

函数和模块

XQuery提供了丰富的内置函数库,用于处理各种数据类型和操作:
  1. (: 字符串函数 :)
  2. string-length("Hello World")  (: 返回 11 :)
  3. upper-case("hello")  (: 返回 "HELLO" :)
  4. concat("Hello", " ", "World")  (: 返回 "Hello World" :)
  5. (: 数值函数 :)
  6. round(3.14159)  (: 返回 3 :)
  7. ceiling(3.14159)  (: 返回 4 :)
  8. floor(3.14159)  (: 返回 3 :)
  9. (: 节点函数 :)
  10. name(/bookstore/book[1])  (: 返回第一个book元素的名称 :)
  11. count(/bookstore/book)  (: 返回book元素的数量 :)
复制代码

XQuery允许定义自己的函数:
  1. (: 定义计算折扣价的函数 :)
  2. declare function local:calculateDiscount($price as xs:decimal, $discountRate as xs:decimal) as xs:decimal {
  3.     $price * (1 - $discountRate)
  4. };
  5. (: 使用自定义函数 :)
  6. for $book in /bookstore/book
  7. return
  8.     <book>
  9.         {$book/title}
  10.         <originalPrice>{$book/price}</originalPrice>
  11.         <discountedPrice>{local:calculateDiscount($book/price, 0.1)}</discountedPrice>
  12.     </book>
复制代码

XQuery支持模块化编程,可以将函数和变量组织到模块中:
  1. (: 定义一个模块 - library.xqm :)
  2. module namespace lib = "http://example.com/library";
  3. declare function lib:calculateDiscount($price as xs:decimal, $discountRate as xs:decimal) as xs:decimal {
  4.     $price * (1 - $discountRate)
  5. };
  6. declare function lib:formatPrice($price as xs:decimal) as xs:string {
  7.     concat("$", format-number($price, "#,##0.00"))
  8. };
复制代码
  1. (: 导入并使用模块 :)
  2. import module namespace lib = "http://example.com/library" at "library.xqm";
  3. for $book in /bookstore/book
  4. let $discountedPrice := lib:calculateDiscount($book/price, 0.1)
  5. return
  6.     <book>
  7.         {$book/title}
  8.         <originalPrice>{lib:formatPrice($book/price)}</originalPrice>
  9.         <discountedPrice>{lib:formatPrice($discountedPrice)}</discountedPrice>
  10.     </book>
复制代码

XQuery高级技巧

高级FLWOR技巧

在FLWOR表达式中,可以使用at关键字获取当前位置:
  1. (: 为书籍添加编号 :)
  2. for $book at $pos in /bookstore/book
  3. return
  4.     <book position="{$pos}">
  5.         {$book/title}
  6.     </book>
复制代码

XQuery 3.0引入了窗口子句,用于在序列上滑动窗口:
  1. (: 计算移动平均 :)
  2. for $price at $i in /products/product/price
  3. let $window := /products/product/price[position() >= $i - 2 and position() <= $i]
  4. where $i >= 3
  5. return
  6.     <movingAverage position="{$i}">
  7.         {avg($window)}
  8.     </movingAverage>
复制代码

XQuery支持递归函数,用于处理递归数据结构:
  1. (: 计算目录总大小的递归函数 :)
  2. declare function local:calculateTotalSize($node as node()) as xs:integer {
  3.     if ($node/self::file) then
  4.         xs:integer($node/@size)
  5.     else
  6.         sum(local:calculateTotalSize($node/*))
  7. };
  8. (: 使用递归函数计算目录总大小 :)
  9. local:calculateTotalSize(/directory)
复制代码

高级查询技术

XQuery支持多种连接操作,类似于SQL中的JOIN:
  1. (: 内连接 - 等值连接 :)
  2. for $book in /bookstore/book
  3. for $author in /authors/author
  4. where $book/author_id = $author/@id
  5. return
  6.     <bookAuthor>
  7.         {$book/title}
  8.         {$author/name}
  9.     </bookAuthor>
  10. (: 左外连接 :)
  11. for $book in /bookstore/book
  12. let $author := /authors/author[@id = $book/author_id]
  13. return
  14.     <bookAuthor>
  15.         {$book/title}
  16.         {$author/name}
  17.     </bookAuthor>
复制代码

XQuery提供了多种聚合函数,用于计算序列的统计值:
  1. (: 计算书籍的平均价格、最高价格和最低价格 :)
  2. <bookStatistics>
  3.     <averagePrice>{avg(/bookstore/book/price)}</averagePrice>
  4.     <maxPrice>{max(/bookstore/book/price)}</maxPrice>
  5.     <minPrice>{min(/bookstore/book/price)}</minPrice>
  6.     <totalBooks>{count(/bookstore/book)}</totalBooks>
  7. </bookStatistics>
复制代码

结合Group By子句和聚合函数,可以进行复杂的数据分析:
  1. (: 按类别分组并计算统计信息 :)
  2. for $book in /bookstore/book
  3. group by $category := $book/category
  4. return
  5.     <category name="{$category}">
  6.         <count>{count($book)}</count>
  7.         <averagePrice>{avg($book/price)}</averagePrice>
  8.         <totalValue>{sum($book/price)}</totalValue>
  9.         <minPrice>{min($book/price)}</minPrice>
  10.         <maxPrice>{max($book/price)}</maxPrice>
  11.     </category>
复制代码

高级数据处理

XQuery可以处理带有命名空间的XML文档:
  1. (: 声明命名空间前缀 :)
  2. declare namespace ns = "http://example.com/books";
  3. (: 使用命名空间前缀查询 :)
  4. for $book in /ns:bookstore/ns:book
  5. return $book/ns:title
  6. (: 使用通配符查询任何命名空间中的元素 :)
  7. for $book in /*:bookstore/*:book
  8. return $book/*:title
复制代码

XQuery 3.1增加了对JSON的支持,可以处理XML和JSON数据:
  1. (: 解析JSON数据 :)
  2. let $json := '{
  3.     "books": [
  4.         {"title": "Book 1", "price": 29.99},
  5.         {"title": "Book 2", "price": 39.99}
  6.     ]
  7. }'
  8. let $data := json:parse($json)
  9. return $data?books?1?title  (: 返回 "Book 1" :)
  10. (: 将XML转换为JSON :)
  11. let $xml := <books><book><title>Book 1</title><price>29.99</price></book></books>
  12. return json:serialize($xml)
复制代码

XQuery提供了丰富的日期和时间处理功能:
  1. (: 获取当前日期和时间 :)
  2. current-date()  (: 当前日期 :)
  3. current-time()  (: 当前时间 :)
  4. current-dateTime()  (: 当前日期和时间 :)
  5. (: 格式化日期 :)
  6. format-date(current-date(), "[Y0001]-[M01]-[D01]")  (: 格式: YYYY-MM-DD :)
  7. (: 计算日期差 :)
  8. let $start := xs:date("2023-01-01")
  9. let $end := xs:date("2023-12-31")
  10. return $end - $start  (: 返回天数差 :)
复制代码

性能优化技巧

在XQuery数据库中,索引可以显著提高查询性能:
  1. (: 创建索引 - 语法可能因实现而异 :)
  2. create index on /bookstore/book/price
  3. create index on /bookstore/book/category
  4. create index on /bookstore/book/author_id
复制代码

优化XQuery查询的一些技巧:
  1. (: 使用谓词尽早过滤数据 :)
  2. (: 不好的做法 - 先处理所有数据再过滤 :)
  3. for $book in /bookstore/book
  4. let $discountedPrice := $book/price * 0.9
  5. where $book/price > 30
  6. return <book>{$book/title, $discountedPrice}</book>
  7. (: 好的做法 - 先过滤再处理 :)
  8. for $book in /bookstore/book[price > 30]
  9. let $discountedPrice := $book/price * 0.9
  10. return <book>{$book/title, $discountedPrice}</book>
复制代码

在复杂查询中,使用变量缓存重复使用的表达式:
  1. (: 不好的做法 - 重复计算复杂表达式 :)
  2. for $book in /bookstore/book
  3. where /bookstore/categories/category[@id = $book/category_id]/@featured = "true"
  4. return $book/title
  5. (: 好的做法 - 使用变量缓存结果 :)
  6. let $featuredCategories := /bookstore/categories/category[@featured = "true"]/@id
  7. for $book in /bookstore/book
  8. where $book/category_id = $featuredCategories
  9. return $book/title
复制代码

避免在循环中构造不必要的节点:
  1. (: 不好的做法 - 在循环中构造节点 :)
  2. for $book in /bookstore/book
  3. return
  4.     <result>
  5.         <bookInfo>
  6.             <title>{$book/title}</title>
  7.             <price>{$book/price}</price>
  8.         </bookInfo>
  9.     </result>
  10. (: 好的做法 - 直接返回需要的节点 :)
  11. for $book in /bookstore/book
  12. return
  13.     <bookInfo>
  14.         <title>{$book/title}</title>
  15.         <price>{$book/price}</price>
  16.     </bookInfo>
复制代码

实战案例

案例1:XML数据转换

假设我们需要将一个XML格式的产品目录转换为HTML格式,以便在网页上显示。

源XML数据:
  1. <catalog>
  2.     <product id="p1">
  3.         <name>Laptop</name>
  4.         <price currency="USD">999.99</price>
  5.         <description>High-performance laptop with 16GB RAM</description>
  6.         <category>Electronics</category>
  7.         <inStock>true</inStock>
  8.     </product>
  9.     <product id="p2">
  10.         <name>Smartphone</name>
  11.         <price currency="USD">699.99</price>
  12.         <description>Latest smartphone with 5G capability</description>
  13.         <category>Electronics</category>
  14.         <inStock>true</inStock>
  15.     </product>
  16.     <product id="p3">
  17.         <name>Desk Chair</name>
  18.         <price currency="USD">199.99</price>
  19.         <description>Ergonomic office chair</description>
  20.         <category>Furniture</category>
  21.         <inStock>false</inStock>
  22.     </product>
  23. </catalog>
复制代码

XQuery转换代码:
  1. (: 将产品目录转换为HTML格式 :)
  2. <html>
  3.     <head>
  4.         <title>Product Catalog</title>
  5.         <style>
  6.             .product {{ border: 1px solid #ccc; margin: 10px; padding: 10px; }}
  7.             .name {{ font-weight: bold; font-size: 1.2em; }}
  8.             .price {{ color: green; }}
  9.             .out-of-stock {{ color: red; }}
  10.         </style>
  11.     </head>
  12.     <body>
  13.         <h1>Product Catalog</h1>
  14.         {
  15.             for $product in /catalog/product
  16.             return
  17.                 <div class="product">
  18.                     <div class="name">{$product/name/text()}</div>
  19.                     <div class="price">Price: {$product/price/text()} {$product/price/@currency}</div>
  20.                     <div>Description: {$product/description/text()}</div>
  21.                     <div>Category: {$product/category/text()}</div>
  22.                     {
  23.                         if ($product/inStock = "true") then
  24.                             <div class="in-stock">In Stock</div>
  25.                         else
  26.                             <div class="out-of-stock">Out of Stock</div>
  27.                     }
  28.                 </div>
  29.         }
  30.     </body>
  31. </html>
复制代码

案例2:数据聚合和报表生成

假设我们需要生成一个销售报表,按产品类别汇总销售数据。

源XML数据:
  1. <sales>
  2.     <sale>
  3.         <product_id>p1</product_id>
  4.         <date>2023-01-15</date>
  5.         <quantity>2</quantity>
  6.         <unit_price>999.99</unit_price>
  7.     </sale>
  8.     <sale>
  9.         <product_id>p2</product_id>
  10.         <date>2023-01-16</date>
  11.         <quantity>1</quantity>
  12.         <unit_price>699.99</unit_price>
  13.     </sale>
  14.     <sale>
  15.         <product_id>p1</product_id>
  16.         <date>2023-01-17</date>
  17.         <quantity>1</quantity>
  18.         <unit_price>999.99</unit_price>
  19.     </sale>
  20.     <sale>
  21.         <product_id>p3</product_id>
  22.         <date>2023-01-18</date>
  23.         <quantity>3</quantity>
  24.         <unit_price>199.99</unit_price>
  25.     </sale>
  26.     <sale>
  27.         <product_id>p2</product_id>
  28.         <date>2023-01-19</date>
  29.         <quantity>2</quantity>
  30.         <unit_price>699.99</unit_price>
  31.     </sale>
  32. </sales>
复制代码

产品目录XML(参考案例1):
  1. <catalog>
  2.     <product id="p1">
  3.         <name>Laptop</name>
  4.         <category>Electronics</category>
  5.     </product>
  6.     <product id="p2">
  7.         <name>Smartphone</name>
  8.         <category>Electronics</category>
  9.     </product>
  10.     <product id="p3">
  11.         <name>Desk Chair</name>
  12.         <category>Furniture</category>
  13.     </product>
  14. </catalog>
复制代码

XQuery报表生成代码:
  1. (: 生成按产品类别分组的销售报表 :)
  2. <salesReport>
  3.     <generatedOn>{current-date()}</generatedOn>
  4.     {
  5.         (: 首先连接销售数据和产品目录 :)
  6.         let $salesWithProducts :=
  7.             for $sale in /sales/sale
  8.             let $product := /catalog/product[@id = $sale/product_id]
  9.             return
  10.                 <saleWithProduct>
  11.                     {$sale/*}
  12.                     <category>{$product/category/text()}</category>
  13.                     <name>{$product/name/text()}</name>
  14.                     <total>{$sale/quantity * $sale/unit_price}</total>
  15.                 </saleWithProduct>
  16.         
  17.         (: 然后按类别分组并计算统计信息 :)
  18.         for $sale in $salesWithProducts
  19.         group by $category := $sale/category
  20.         order by $category
  21.         return
  22.             <categorySummary>
  23.                 <category>{$category}</category>
  24.                 <totalSales>{sum($sale/total)}</totalSales>
  25.                 <totalQuantity>{sum($sale/quantity)}</totalQuantity>
  26.                 <averageSale>{avg($sale/total)}</averageSale>
  27.                 <salesCount>{count($sale)}</salesCount>
  28.                 <products>
  29.                     {
  30.                         (: 按产品分组并计算统计信息 :)
  31.                         for $productSale in $sale
  32.                         group by $productName := $productSale/name
  33.                         order by $productName
  34.                         return
  35.                             <productSummary>
  36.                                 <name>{$productName}</name>
  37.                                 <totalSales>{sum($productSale/total)}</totalSales>
  38.                                 <totalQuantity>{sum($productSale/quantity)}</totalQuantity>
  39.                                 <salesCount>{count($productSale)}</salesCount>
  40.                             </productSummary>
  41.                     }
  42.                 </products>
  43.             </categorySummary>
  44.     }
  45.     <grandTotal>
  46.         <totalSales>{sum(/sales/sale/(quantity * unit_price))}</totalSales>
  47.         <totalQuantity>{sum(/sales/sale/quantity)}</totalQuantity>
  48.     </grandTotal>
  49. </salesReport>
复制代码

案例3:复杂数据处理和转换

假设我们需要处理一个包含嵌套结构的XML文档,提取特定信息并重新组织结构。

源XML数据:
  1. <library>
  2.     <books>
  3.         <book isbn="978-0321680548">
  4.             <title>XML Bible</title>
  5.             <authors>
  6.                 <author>
  7.                     <firstName>Elliotte</firstName>
  8.                     <lastName>Harold</lastName>
  9.                 </author>
  10.             </authors>
  11.             <publisher>Wiley</publisher>
  12.             <year>2011</year>
  13.             <categories>
  14.                 <category>XML</category>
  15.                 <category>Programming</category>
  16.             </categories>
  17.             <reviews>
  18.                 <review rating="5">
  19.                     <user>user123</user>
  20.                     <comment>Excellent book for XML beginners</comment>
  21.                 </review>
  22.                 <review rating="4">
  23.                     <user>user456</user>
  24.                     <comment>Comprehensive coverage of XML technologies</comment>
  25.                 </review>
  26.             </reviews>
  27.         </book>
  28.         <book isbn="978-0596101497">
  29.             <title>XQuery</title>
  30.             <authors>
  31.                 <author>
  32.                     <firstName>Priscilla</firstName>
  33.                     <lastName>Walmsley</lastName>
  34.                 </author>
  35.             </authors>
  36.             <publisher>O'Reilly</publisher>
  37.             <year>2007</year>
  38.             <categories>
  39.                 <category>XQuery</category>
  40.                 <category>Programming</category>
  41.             </categories>
  42.             <reviews>
  43.                 <review rating="5">
  44.                     <user>user789</user>
  45.                     <comment>The definitive guide to XQuery</comment>
  46.                 </review>
  47.             </reviews>
  48.         </book>
  49.         <book isbn="978-1491910266">
  50.             <title>XML and JSON Recipes</title>
  51.             <authors>
  52.                 <author>
  53.                     <firstName>Salvatore</firstName>
  54.                     <lastName>Mangano</lastName>
  55.                 </author>
  56.             </authors>
  57.             <publisher>O'Reilly</publisher>
  58.             <year>2014</year>
  59.             <categories>
  60.                 <category>XML</category>
  61.                 <category>JSON</category>
  62.                 <category>Programming</category>
  63.             </categories>
  64.             <reviews>
  65.                 <review rating="4">
  66.                     <user>user123</user>
  67.                     <comment>Great practical examples</comment>
  68.                 </review>
  69.                 <review rating="3">
  70.                     <user>user456</user>
  71.                     <comment>Could use more advanced content</comment>
  72.                 </review>
  73.             </reviews>
  74.         </book>
  75.     </books>
  76.     <users>
  77.         <user id="user123">
  78.             <name>John Doe</name>
  79.             <email>john@example.com</email>
  80.         </user>
  81.         <user id="user456">
  82.             <name>Jane Smith</name>
  83.             <email>jane@example.com</email>
  84.         </user>
  85.         <user id="user789">
  86.             <name>Bob Johnson</name>
  87.             <email>bob@example.com</email>
  88.         </user>
  89.     </users>
  90. </library>
复制代码

XQuery处理代码:
  1. (: 处理图书馆数据,生成作者和他们的书籍列表,以及用户评论统计 :)
  2. <libraryReport>
  3.     <authors>
  4.         {
  5.             (: 提取所有作者并按姓氏排序 :)
  6.             let $allAuthors :=
  7.                 for $book in /library/books/book
  8.                 for $author in $book/authors/author
  9.                 return
  10.                     <author>
  11.                         <firstName>{$author/firstName/text()}</firstName>
  12.                         <lastName>{$author/lastName/text()}</lastName>
  13.                         <fullName>{concat($author/firstName, " ", $author/lastName)}</fullName>
  14.                         <book>
  15.                             <title>{$book/title/text()}</title>
  16.                             <isbn>{$book/@isbn}</isbn>
  17.                             <year>{$book/year/text()}</year>
  18.                         </book>
  19.                     </author>
  20.             
  21.             (: 按作者全名分组并收集他们的书籍 :)
  22.             for $author in $allAuthors
  23.             group by $fullName := $author/fullName
  24.             order by $author[1]/lastName, $author[1]/firstName
  25.             return
  26.                 <author>
  27.                     <name>{$fullName}</name>
  28.                     <books>
  29.                         {
  30.                             for $book in $author/book
  31.                             order by $book/year descending
  32.                             return $book
  33.                         }
  34.                     </books>
  35.                     <bookCount>{count($author)}</bookCount>
  36.                 </author>
  37.         }
  38.     </authors>
  39.    
  40.     <userReviewStats>
  41.         {
  42.             (: 为每个用户计算评论统计信息 :)
  43.             for $user in /library/users/user
  44.             let $userReviews := /library/books/book/reviews/review[user = $user/@id]
  45.             let $reviewCount := count($userReviews)
  46.             let $avgRating := if ($reviewCount > 0) then avg($userReviews/@rating) else 0
  47.             return
  48.                 <user>
  49.                     <id>{$user/@id}</id>
  50.                     <name>{$user/name/text()}</name>
  51.                     <email>{$user/email/text()}</email>
  52.                     <reviewCount>{$reviewCount}</reviewCount>
  53.                     <averageRating>{round-half-to-even($avgRating, 1)}</averageRating>
  54.                 </user>
  55.         }
  56.     </userReviewStats>
  57.    
  58.     <categoryStats>
  59.         {
  60.             (: 按类别统计书籍数量 :)
  61.             let $allCategories :=
  62.                 for $book in /library/books/book
  63.                 for $category in $book/categories/category
  64.                 return $category/text()
  65.             
  66.             for $category in distinct-values($allCategories)
  67.             let $count := count(/library/books/book[categories/category = $category])
  68.             order by $category
  69.             return
  70.                 <category>
  71.                     <name>{$category}</name>
  72.                     <bookCount>{$count}</bookCount>
  73.                 </category>
  74.         }
  75.     </categoryStats>
  76. </libraryReport>
复制代码

案例4:与外部数据源集成

XQuery可以与外部数据源集成,如Web服务、数据库等。以下是一个示例,展示如何从REST API获取数据并与本地XML数据结合。

假设我们有一个本地XML文件包含产品信息,我们需要从外部API获取实时价格并更新产品信息。

本地XML数据:
  1. <products>
  2.     <product id="p1">
  3.         <name>Laptop</name>
  4.         <description>High-performance laptop</description>
  5.         <category>Electronics</category>
  6.     </product>
  7.     <product id="p2">
  8.         <name>Smartphone</name>
  9.         <description>Latest smartphone model</description>
  10.         <category>Electronics</category>
  11.     </product>
  12.     <product id="p3">
  13.         <name>Desk Chair</name>
  14.         <description>Ergonomic office chair</description>
  15.         <category>Furniture</category>
  16.     </product>
  17. </products>
复制代码

假设我们有一个REST API,可以通过产品ID获取价格信息,返回JSON格式数据:
  1. GET /api/prices/p1
  2. Response:
  3. {
  4.     "productId": "p1",
  5.     "price": 999.99,
  6.     "currency": "USD",
  7.     "lastUpdated": "2023-01-20T10:30:00Z"
  8. }
复制代码

XQuery代码(使用BaseX的http:client模块):
  1. (: 导入HTTP客户端模块 :)
  2. import module namespace http = "http://expath.org/ns/http-client";
  3. (: 定义获取价格的函数 :)
  4. declare function local:getPrice($productId as xs:string) as element()? {
  5.     let $url := concat("http://example.com/api/prices/", $productId)
  6.     let $response := http:send-request(<http:request method="get" href="{$url}"/>)
  7.     let $json := $response[2]
  8.     return
  9.         if ($response[1]/@status = "200") then
  10.             let $parsed := json:parse($json)
  11.             return
  12.                 <price>
  13.                     <value>{$parsed?price}</value>
  14.                     <currency>{$parsed?currency}</currency>
  15.                     <lastUpdated>{$parsed?lastUpdated}</lastUpdated>
  16.                 </price>
  17.         else ()
  18. };
  19. (: 更新产品信息,添加价格数据 :)
  20. <productsWithPrices>
  21.     {
  22.         for $product in /products/product
  23.         let $priceInfo := local:getPrice($product/@id)
  24.         return
  25.             <product id="{$product/@id}">
  26.                 {$product/*}
  27.                 {
  28.                     if ($priceInfo) then $priceInfo
  29.                     else <price status="unavailable"/>
  30.                 }
  31.             </product>
  32.     }
  33. </productsWithPrices>
复制代码

案例5:大型XML文档处理

处理大型XML文档时,内存使用和性能是关键考虑因素。以下是一个示例,展示如何使用流式处理技术处理大型XML文件。

假设我们有一个非常大的XML文件,包含数百万条交易记录,我们需要计算每个账户的总交易金额。

大型XML文件示例(简化):
  1. <transactions>
  2.     <transaction>
  3.         <account_id>acc123</account_id>
  4.         <date>2023-01-01</date>
  5.         <amount>100.00</amount>
  6.         <type>deposit</type>
  7.     </transaction>
  8.     <transaction>
  9.         <account_id>acc456</account_id>
  10.         <date>2023-01-01</date>
  11.         <amount>50.00</amount>
  12.         <type>withdrawal</type>
  13.     </transaction>
  14.     <!-- 数百万条交易记录... -->
  15. </transactions>
复制代码

使用BaseX的流式处理功能:
  1. (: 使用流式处理计算每个账户的总交易金额 :)
  2. declare option db:chop "false";
  3. (: 创建一个映射来存储账户总额 :)
  4. let $accountTotals := map:new()
  5. (: 流式处理交易记录 :)
  6. for $transaction in /transactions/transaction
  7. let $accountId := $transaction/account_id/text()
  8. let $amount := xs:decimal($transaction/amount/text())
  9. let $type := $transaction/type/text()
  10. let $signedAmount :=
  11.     if ($type = "deposit") then $amount
  12.     else -$amount
  13. (: 更新账户总额 :)
  14. let $_ :=
  15.     if (map:contains($accountTotals, $accountId)) then
  16.         map:put($accountTotals, $accountId, map:get($accountTotals, $accountId) + $signedAmount)
  17.     else
  18.         map:put($accountTotals, $accountId, $signedAmount)
  19. return ()
  20. (: 生成账户汇总报告 :)
  21. <accountSummary>
  22.     {
  23.         for $accountId in map:keys($accountTotals)
  24.         let $total := map:get($accountTotals, $accountId)
  25.         order by $accountId
  26.         return
  27.             <account id="{$accountId}">
  28.                 <totalBalance>{$total}</totalBalance>
  29.             </account>
  30.     }
  31. </accountSummary>
复制代码

最佳实践和性能优化

XQuery最佳实践

将复杂的XQuery代码分解为可重用的模块和函数:
  1. (: 定义一个工具模块 - utils.xqm :)
  2. module namespace utils = "http://example.com/utils";
  3. declare function utils:format-currency($amount as xs:decimal, $currency as xs:string) as xs:string {
  4.     concat($currency, format-number($amount, "#,##0.00"))
  5. };
  6. declare function utils:format-date($date as xs:date) as xs:string {
  7.     format-date($date, "[MNn] [D], [Y0001]")
  8. };
  9. declare function utils:calculate-tax($amount as xs:decimal, $rate as xs:decimal) as xs:decimal {
  10.     round-half-to-even($amount * $rate, 2)
  11. };
复制代码
  1. (: 在主查询中导入和使用模块 :)
  2. import module namespace utils = "http://example.com/utils" at "utils.xqm";
  3. for $invoice in /invoices/invoice
  4. let $subtotal := sum($invoice/items/item/(quantity * unit_price))
  5. let $tax := utils:calculate-tax($subtotal, 0.08)
  6. let $total := $subtotal + $tax
  7. return
  8.     <invoiceSummary>
  9.         <invoiceNumber>{$invoice/@id}</invoiceNumber>
  10.         <date>{utils:format-date(xs:date($invoice/date))}</date>
  11.         <subtotal>{utils:format-currency($subtotal, "$")}</subtotal>
  12.         <tax>{utils:format-currency($tax, "$")}</tax>
  13.         <total>{utils:format-currency($total, "$")}</total>
  14.     </invoiceSummary>
复制代码

在函数参数和变量中使用类型声明,可以提高代码的可读性和性能:
  1. (: 不好的做法 - 没有类型声明 :)
  2. declare function local:calculate-discount($price, $rate) {
  3.     $price * (1 - $rate)
  4. };
  5. (: 好的做法 - 使用类型声明 :)
  6. declare function local:calculate-discount($price as xs:decimal, $rate as xs:decimal) as xs:decimal {
  7.     $price * (1 - $rate)
  8. };
复制代码

为代码添加注释和文档,提高可维护性:
  1. (:~
  2. : 计算折扣价格
  3. : @param $price 原始价格
  4. : @param $rate 折扣率(0到1之间的小数)
  5. : @return 折扣后的价格
  6. : @example local:calculate-discount(100.00, 0.1) 返回 90.00
  7. :)
  8. declare function local:calculate-discount($price as xs:decimal, $rate as xs:decimal) as xs:decimal {
  9.     (: 验证折扣率是否在有效范围内 :)
  10.     if ($rate < 0 or $rate > 1) then
  11.         fn:error(xs:QName("local:INVALID_RATE"), "Discount rate must be between 0 and 1")
  12.     else
  13.         $price * (1 - $rate)
  14. };
复制代码

使用适当的错误处理机制,提高代码的健壮性:
  1. (: 使用try-catch处理错误 :)
  2. try {
  3.     (: 尝试解析日期 :)
  4.     let $date := xs:date($input)
  5.     return format-date($date, "[Y0001]-[M01]-[D01]")
  6. } catch * {
  7.     (: 处理日期解析错误 :)
  8.     fn:error(xs:QName("local:INVALID_DATE"), "Invalid date format: " || $input)
  9. };
  10. (: 使用fn:error抛出自定义错误 :)
  11. declare function local:validate-price($price as xs:decimal) as xs:decimal {
  12.     if ($price < 0) then
  13.         fn:error(xs:QName("local:INVALID_PRICE"), "Price cannot be negative")
  14.     else
  15.         $price
  16. };
复制代码

性能优化技巧

在XQuery数据库中,为经常查询的字段创建索引:
  1. (: 创建索引 - 语法可能因实现而异 :)
  2. create index on /invoices/invoice/@id
  3. create index on /invoices/invoice/date
  4. create index on /invoices/invoice/customer_id
复制代码

编写高效的XPath表达式,避免不必要的节点遍历:
  1. (: 不好的做法 - 使用双斜杠搜索整个文档 :)
  2. for $item in //item
  3. where $item/price > 100
  4. return $item
  5. (: 好的做法 - 使用具体路径 :)
  6. for $item in /invoices/invoice/items/item
  7. where $item/price > 100
  8. return $item
复制代码

在查询的早期阶段使用谓词过滤数据,减少处理的数据量:
  1. (: 不好的做法 - 先处理所有数据再过滤 :)
  2. for $invoice in /invoices/invoice
  3. let $total := sum($invoice/items/item/(quantity * unit_price))
  4. where $total > 1000
  5. return $invoice/@id
  6. (: 好的做法 - 先过滤再处理 :)
  7. for $invoice in /invoices/invoice[sum(items/item/(quantity * unit_price)) > 1000]
  8. return $invoice/@id
复制代码

将循环中重复计算的表达式提取到循环外部:
  1. (: 不好的做法 - 在循环中重复计算 :)
  2. for $invoice in /invoices/invoice
  3. let $taxRate := /config/taxRate
  4. let $subtotal := sum($invoice/items/item/(quantity * unit_price))
  5. let $tax := $subtotal * $taxRate
  6. return
  7.     <invoice>
  8.         <id>{$invoice/@id}</id>
  9.         <tax>{$tax}</tax>
  10.     </invoice>
  11. (: 好的做法 - 将常量提取到循环外部 :)
  12. let $taxRate := /config/taxRate
  13. for $invoice in /invoices/invoice
  14. let $subtotal := sum($invoice/items/item/(quantity * unit_price))
  15. let $tax := $subtotal * $taxRate
  16. return
  17.     <invoice>
  18.         <id>{$invoice/@id}</id>
  19.         <tax>{$tax}</tax>
  20.     </invoice>
复制代码

将复杂或重复使用的表达式结果缓存到变量中:
  1. (: 不好的做法 - 重复计算复杂表达式 :)
  2. for $invoice in /invoices/invoice
  3. where /customers/customer[@id = $invoice/customer_id]/@status = "active"
  4. return $invoice
  5. (: 好的做法 - 使用变量缓存结果 :)
  6. let $activeCustomers := /customers/customer[@status = "active"]/@id
  7. for $invoice in /invoices/invoice
  8. where $invoice/customer_id = $activeCustomers
  9. return $invoice
复制代码

选择合适的函数可以提高性能:
  1. (: 不好的做法 - 使用string()函数 :)
  2. for $book in /bookstore/book
  3. where string($book/price) > "30"
  4. return $book
  5. (: 好的做法 - 直接比较数值 :)
  6. for $book in /bookstore/book
  7. where $book/price > 30
  8. return $book
复制代码

利用XML文档的固有顺序,避免不必要的排序:
  1. (: 不好的做法 - 对已经是正确顺序的数据进行排序 :)
  2. for $item in /items/item
  3. order by $item/@id
  4. return $item
  5. (: 好的做法 - 利用文档顺序 :)
  6. for $item in /items/item
  7. return $item
复制代码

总结和进阶学习资源

总结

XQuery是一种强大的XML查询和处理语言,它结合了XPath的导航能力和SQL的查询能力,同时具备函数式编程语言的特性。通过本文的学习,我们了解了XQuery的基础概念、核心功能、高级技巧以及实战应用。

主要内容包括:

1. XQuery基础:语法、数据模型、基本概念
2. 核心功能:路径表达式、FLWOR表达式、条件表达式、量词表达式
3. 节点构造和修改:创建新节点、修改现有节点
4. 函数和模块:内置函数、用户自定义函数、模块化编程
5. 高级技巧:高级FLWOR技巧、高级查询技术、高级数据处理
6. 实战案例:XML数据转换、数据聚合和报表生成、复杂数据处理、与外部数据源集成、大型XML文档处理
7. 最佳实践和性能优化:模块化编程、类型声明、错误处理、性能优化技巧

掌握XQuery可以帮助开发人员高效地处理XML数据,解决实际工作中的各类挑战,提升开发效率。

进阶学习资源

1. W3C XQuery 3.1 规范- XQuery的官方规范文档
2. W3C XPath and XQuery Functions and Operators 3.1- XQuery内置函数的官方参考
3. XQuery Update Facility 3.0- XQuery更新功能的规范

1. “XQuery” by Priscilla Walmsley - O’Reilly Media,XQuery的权威指南
2. “XQuery: The XML Query Language” by Michael Brundage - Addison-Wesley Professional,深入介绍XQuery的各个方面
3. “XML and JSON Recipes” by Salvatore Mangano - O’Reilly Media,包含XQuery处理XML和JSON的实际示例

1. BaseX文档- BaseX XML数据库和XQuery处理器的详细文档
2. eXist-db文档- eXist-db XML数据库的文档
3. Saxonica文档- Saxon XSLT和XQuery处理器的文档

1. W3Schools XQuery教程- XQuery基础教程
2. XML Master课程- 提供XML相关技术认证,包括XQuery
3. Pluralsight XQuery课程- 提供XQuery在线课程

1. Stack Overflow XQuery标签- XQuery问答社区
2. BaseX论坛- BaseX用户和开发者论坛
3. eXist-db邮件列表- eXist-db社区讨论

通过这些资源,你可以进一步深入学习XQuery,掌握更多高级技巧,解决更复杂的问题,成为XQuery专家。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

频道订阅

频道订阅

加入社群

加入社群

联系我们|TG频道|RSS

Powered by Pixtech

© 2025 Pixtech Team.