跳轉到內容

XQuery/樹檢視

來自華夏公益教科書

您需要一個通用函式來建立層次資料的表格檢視。

我們將編寫一個遞迴函式來顯示每個節點,然後在 HTML 表格中顯示每個子節點。

有些系統稱之為 XML 資料的“網格檢視”。

元素到巢狀表格函式

[編輯 | 編輯原始碼]

以下函式生成一個 HTML 表格,其中包含子節點的巢狀子表格。

declare function local:element-to-nested-table($element) {
   if (exists ($element/(@*|*)))
     then 
     <table>
        {if (exists($element/text()))
         then <tr class="text">
                  <th></th>
                  <td>{$element/text()}</td>
              </tr>
         else ()
       }
       {for $attribute in $element/@*
       return
          <tr class="attribute">
             <th>@{name($attribute)}</th>
             <td>{string($attribute)}</td>
          </tr>
       }
       {for $node in $element/*
       return 
          <tr class="element">
             <th>{name($node)}</th> 
             <td>{local:element-to-nested-table($node)}</td>
          </tr>       
        }
    </table>
    else $element/text()
  };

請注意,顯示不同型別專案(文字、屬性、元素)的行被分類,以便可以對其進行樣式設定。

文件顯示

[編輯 | 編輯原始碼]

此函式可用於指令碼中,為任何 XML 文件提供檢視器。

declare namespace hc ="http://exist-db.org/xquery/httpclient";
declare option exist:serialize "method=xhtml media-type=text/html indent=yes";

 (: function declaration :)

let $uri := request:get-parameter("uri",())
let $element:= httpclient:get(xs:anyURI($uri),true(),())/hc:body/html
return
 <html>
    <head>
    <title>Tree view</title>
    <style type="text/css">
      th {{border-style:double}}
      tr {{border-style:dotted}}
      tr .attribute {{font-style:italic}}
      td {{border-style:ridge}}
     </style>
    </head>
    <body>
    <h1>Tree view of {$uri} </h1>
     {local:element-to-nested-table($element)}
     </body>
 </html>

例如

  1. UWE 的新聞提要
  2. 威士忌資料
  3. 員工資料
  4. 英國氣象局航運預報 格式錯誤的 XML
華夏公益教科書