跳转到内容

XQuery/图像库

来自维基教科书,开放世界中的开放书籍

您想要一个脚本,它将显示图像集合中所有图像的小缩略图。这些图像可能具有许多文件后缀(jpg、png、gif 等)。

我们将编写一个 XQuery,它会找到集合中具有正确文件类型的所有子资源。

源代码

[编辑 | 编辑源代码]
xquery version "1.0";
declare option exist:serialize "method=xhtml media-type=text/html";

(: look for the collection parameter in the incoming URL.  If not assume a default collection like /db/images. :)
let $collection := request:get-parameter('collection', '/db/images')

(: you can also change the number of images per row :)
let $images-per-row := xs:integer(request:get-parameter('images-per-row', 10))

(: first get all the files in the collection :)
let $all-files := xmldb:get-child-resources($collection)

(: now just get the files with known image file type extensions :)
let $image-files :=
   for $file in $all-files[
      ends-with(.,'.png') or 
      ends-with(.,'.jpg') or 
      ends-with(.,'.tiff') or 
      ends-with(.,'.gif')]
   return $file
   
   let $image-count := count($image-files)
   let $rows-count := xs:integer(ceiling($image-count div $images-per-row))
return
<html>
   <head>
      <title>Images for collection {$collection}</title>
   </head>
   <body>
      Images in collection: {$collection}
      <table>{
            for $row  in (1 to $rows-count)
            return
              <tr>{
                for $col in (1 to $images-per-row)
                let $n := ($row - 1 ) * $images-per-row + $col               
                return 
                  if ($n <= $image-count)
                  then  
                     let $image := $image-files[position() = $n ]
                     let $path := concat('/exist/rest', $collection, '/', $image)
                     return
                      <td>
                         <a href="{$path}"><img src="{$path}" height="100px" width="100px"/></a>
                      </td>
                   else <td/>  (: blank cells at the end of the last row :)
              }</tr>           
        }</table>
   </body>
</html>
华夏公益教科书