XQuery/驗證層次結構
外觀
< XQuery
雖然模式驗證能檢查模型有效性的某些方面,但業務規則通常比能用 XML 模式表示的規則更復雜。XQuery 是描述更復雜規則的一門功能強大的語言。
其中一個規則是關係應當定義樹結構,例如員工和經理之間的關係。
考慮以下員工集合
<company>
<emp>
<name>Fred</name>
<mgr>Bill</mgr>
</emp>
<emp>
<name>Joe</name>
<mgr>Bill</mgr>
</emp>
<emp>
<name>Alice</name>
<mgr>Joe</mgr>
</emp>
<emp>
<name>Bill</name>
</emp>
</company>
有效層次結構的標準是
- 一個根(老闆);
- 每位員工最多隻有一位經理;
- 每位員工最終彙報給老闆;
- 沒有迴圈
在 XQuery 中,我們可以將從老闆到員工的管理層次結構定義為
declare function local:management($emp as element(emp) ,
$hierarchy as element(emp)* ) as element(emp)* {
if ($emp = $hierarchy ) (: cycle detected :)
then ()
else
let $mgr := $emp/../emp[name=$emp/mgr]
return
if (count($mgr) > 1)
then ()
else
if (empty ($mgr)) (: reached the root :)
then ($emp,$hierarchy)
else local:management($mgr, ($emp,$hierarchy))
};
該函式最初被呼叫為
local:managment($emp,())
將層次結構建立為一個允許檢測迴圈的引數。
最終,管理結構成為樹的條件是
declare function local:management-is-tree($company)) {
let $boss := $company/emp[empty(mgr)]
return
count($boss) = 1
and
(every $emp in $company/emp
satisfies $boss = local:management($emp,())[1]
)
};