XQuery/在 HTML 表格中顯示資料
外觀
< XQuery
您希望在 HTML 表格中顯示您的 XML 資料,並使用彩色背景顯示交替行。
假設您有一個數據檔案,例如以下 XML 檔案,它是術語和定義的示例詞彙表
<terms>
<term>
<term-name>Object Class</term-name>
<definition>A set of ideas, abstractions, or things in the real world
that are identified with explicit boundaries and meaning and whose properties
and behavior follow the same rules</definition>
</term>
<term>
<term-name>Organization</term-name>
<definition>A unit consisting of people and processes established
to perform some functions</definition>
</term>
</terms>
<term> 標籤將在您的詞彙表中的每個術語重複。
您希望在 HTML 表格中顯示這些術語。

以下 XQuery 將執行此任務。
xquery version "1.0";
declare option exist:serialize "method=xhtml media-type=text/html";
let $my-doc := doc('terms.xml')
return
<html>
<head>
<title>Terms</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<th>Term</th>
<th>Definition</th>
</tr>
</thead>
<tbody>{
for $term at $count in $my-doc/terms/term
let $term-name := $term/term-name/text()
order by upper-case($term-name)
return
<tr> {if ($count mod 2) then (attribute bgcolor {'Lavender'}) else ()}
<td>{$term/term-name/text()}</td>
<td>{$term/definition/text()}</td>
</tr>
}</tbody>
</table>
</body>
</html>
有兩個巢狀的 for 迴圈。外部迴圈具有額外的 at count 引數,該引數為每個返回的結果遞增一個計數器。內部迴圈有一個迴圈,它將一個通用的排序項返回給外部迴圈。請注意,內部迴圈首先執行排序,而外部迴圈對每個項進行計數,以便交替行被著色。
請注意,如果您知道原始檔案按正確順序排列,則不需要巢狀的 for 迴圈。只需要一個帶有 at $count 的 for 迴圈。
以下幾行
<tr> {if ($count mod 2)
then (attribute bgcolor {'Lavender'})
else ()}
為奇數行(其 $count 對 2 取模不為零,因此計算結果為真)條件地建立一個淺藍色背景顏色。這是一個動態元素構造的示例。
奇數行
<tr bgcolor="Lavender">
<td>...</td>
</tr>
偶數行
<tr><td>...</td></tr>
它透過為表格中的奇數行條件地新增屬性 bgcolor="Lavender" 來實現這一點。如果測試 ($count mod 2) 為零,即在偶數行上,將不會新增屬性。
建議最佳實踐是在中央級聯樣式表中對錶格的交替行進行著色。在整個站點中保持表格格式標準的最通用方法是為每行新增語義類標籤以將其標記為偶數或奇數。
<tr> {if ($count mod 2)
then (attribute class {'even'})
else (attribute class {'odd'})}
然後,CSS 檔案將包含以下內容
.odd {background-color: Lavender;}