跳轉到內容

XQuery/所有葉路徑

來自華夏公益教科書,開放書籍,開放世界

您希望生成文件或文件集合中所有葉路徑的列表。

此過程對於瞭解新資料集非常有用。具體來說,您會發現 XML 檔案中的葉元素承載了資料樣式標記中的大部分資料。這些葉元素通常用於承載文件中的大多數語義或意義。它們為文件的語義清單奠定了基礎。也就是說,每個葉元素都應該能夠與資料定義相關聯。

葉元素也是索引配置檔案中索引的良好目標。

我們將使用 functx leaf-elements() 函式

  functx:leaf-elements($nodes*) xs:string*

此函式將一個或多個節點作為輸入,並返回一個字串陣列。

示例輸出

[編輯 | 編輯原始碼]

對於包含在 eXist 演示集中的演示劇哈姆雷特,檔案 /db/shakespeare/plays/hamlet.xml 將生成以下輸出

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

葉元素的原始碼

[編輯 | 編輯原始碼]
declare namespace functx = "http://www.functx.com"; 
declare function functx:leaf-elements ($root as node()?) as element()* {
   $root/descendant-or-self::*[not(*)]
};

此查詢使用 descendant-or-self::* 函式,並使用謂詞 [not(*)] 來限定沒有子節點的元素。

示例 XQuery

[編輯 | 編輯原始碼]
xquery version "1.0";
declare namespace functx = "http://www.functx.com";
declare function functx:distinct-element-names($nodes as node()*) as xs:string* {
   distinct-values($nodes/descendant-or-self::*/local-name(.))
};

let $doc := doc('/db/shakespeare/plays/hamlet.xml')

let $distinct-element-names := functx:distinct-element-names($doc)

let $distinct-element-names-count := count($distinct-element-names)

return
<ol>{
  for $distinct-element-name in $distinct-element-names
  order by $distinct-element-name
  return
      <li>{$distinct-element-name}</li>
}</ol>

新增屬性

[編輯 | 編輯原始碼]

您還可以執行一個查詢來獲取所有不同的屬性。屬性都被視為葉資料型別,因為它們永遠不能有子元素。

declare function functx:distinct-attribute-names($nodes as node()*)  as xs:string* {
   distinct-values($nodes//@*/name(.))
};

此查詢實際上表示“獲取輸入節點中的所有不同屬性名稱”。

對於 MODS 演示檔案:doc('/db/mods/01c73f2b05650de2e6124d9d113f40be.xml')

您將獲得以下屬性

  1. type
  2. encoding
  3. authority

</syntaxhighlight>

參考文獻

[編輯 | 編輯原始碼]

文件 在 xqueryfunctions.com 網站上。

華夏公益教科書