XQuery/樹檢視
外觀
< 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>
例如