跳轉到內容

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>


有效層次結構的標準是

  1. 一個根(老闆);
  2. 每位員工最多隻有一位經理;
  3. 每位員工最終彙報給老闆;
  4. 沒有迴圈

在 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]
      )
};

華夏公益教科書