跳轉至內容

XQuery/所有路徑

來自 Wikibooks,開放世界中的開放書籍

您希望生成文件中所有唯一路徑表示式的列表。

此過程對於快速熟悉新的資料集非常有用。確保您的文件樣式轉換訪問所有元素也很重要。此過程還可以用作生成新資料集索引檔案的基礎。

示例輸出

[編輯 | 編輯原始碼]

eXist 演示系統上莎士比亞簡報中的示例檔案/db/shakespeare/plays/hamlet.xml的唯一路徑列表將生成以下結果。

PLAY
PLAY/TITLE
PLAY/FM
PLAY/FM/P
PLAY/PERSONAE
PLAY/PERSONAE/TITLE
PLAY/PERSONAE/PERSONA
PLAY/PERSONAE/PGROUP
PLAY/PERSONAE/PGROUP/PERSONA
PLAY/PERSONAE/PGROUP/GRPDESCR
PLAY/SCNDESCR
PLAY/PLAYSUBT
PLAY/ACT
PLAY/ACT/TITLE
PLAY/ACT/SCENE
PLAY/ACT/SCENE/TITLE
PLAY/ACT/SCENE/STAGEDIR
PLAY/ACT/SCENE/SPEECH
PLAY/ACT/SCENE/SPEECH/SPEAKER
PLAY/ACT/SCENE/SPEECH/LINE
PLAY/ACT/SCENE/SPEECH/STAGEDIR
PLAY/ACT/SCENE/SPEECH/LINE/STAGEDIR

請注意,這些路徑表示式按文件順序排序,即路徑首次出現在文件中的順序。因此,您可以看到 PERSONAE 中的演員表在 ACT/SCENE 元素之前出現。輸出也可以按字母順序排序。

我們將使用 functx 庫。

特別是函式

 functx:distinct-element-paths($nodes)

以節點作為輸入,並返回路徑表示式的字串序列。

參見 xqueryfunctions.com 上的文件

distinct-element-paths 函式

[編輯 | 編輯原始碼]
xquery version "1.0";
declare namespace functx = "http://www.functx.com";
declare function functx:path-to-node($nodes as node()*) as xs:string* {
    $nodes/string-join(ancestor-or-self::*/name(.), '/')
};

declare function functx:distinct-element-paths($nodes as node()*) as xs:string* {
    distinct-values(functx:path-to-node($nodes/descendant-or-self::*))
 };

declare function functx:sort($seq as item()*) as item()* {
  for $item in $seq
  order by $item
  return $item
};

let $in-xml := collection("NAMEOFCOLLECTION")

return functx:sort(functx:distinct-element-paths($in-xml))

此查詢的核心是單個表示式

  ancestor-or-self::*/name(.)

它實際上表示“獲取文件中所有節點的元素名稱”。下一步是將此列表轉換為唯一元素路徑的列表。這是透過函式functx:distinct-element-paths()完成的。

使用單個測試文件

[編輯 | 編輯原始碼]

使用 document()

使用文件集合

[編輯 | 編輯原始碼]

使用 collection() 函式

建立 Web 服務

[編輯 | 編輯原始碼]

David Elwell 於 2010 年 7 月 22 日在 open-exist 列表中釋出了此建議

華夏公益教科書