跳轉至內容

XQuery/Simile Exhibit

來自華夏公益教科書

您想要建立一個 Simile Exhibit 的 XML 檔案輸出。為此,我們需要將 XML 轉換為 JSON 檔案格式。

您有一個書籍貢獻者檔案,您想要建立其位置的地圖。

<contributors>
    <contributor>
        <author-name>John Doe</author-name>
        <bio>John is a software developer interested in the semantic web.</bio>
        <location>New York, NY</location>
        <image-url>http://www.example.com/images/john-doe.jpg</image-url>
    </contributor>
    <contributor>
        <author-name>Sue Anderson</author-name>
        <bio>Sue is an XML consultant and is interested in XQuery.</bio>
        <location>San Francisco, CA</location>
        <image-url>http://www.example.com/images/sue-anderson.jpg</image-url>
    </contributor>
</contributors>

XQuery 輸出 JSON 檔案

[編輯 | 編輯原始碼]

首先,我們必須將我們的 XML 檔案轉換為 JSON 格式。這有點棘手,因為 JSON 要求將大括號字元新增到輸出中。這可以透過建立包含字串的特殊變數來完成。

在 XQuery 標頭中,我們還必須將序列化方法從傳統的 XML 更改為 text/plain。

我們還必須將專案輸出包裝在 string-join() 函式中,以防止最後一個逗號被序列化。

JSON 檔案只是另一種用於儲存層次資料的檔案格式。就像 XML 一樣。JSON 主要用於不熟悉 XML 或沒有 XML 編輯工具來驗證檔案格式的 JavaScript 開發人員。JSON 允許巢狀複雜資料,但不支援 XML 的許多功能,例如名稱空間。

與 XQuery 不同,JSON 檔案格式不允許在標籤中使用“破折號”字元,除非您在標籤周圍加上引號。因此請注意,image-url 屬性標籤周圍有引號。

xquery version "1.0";
declare option exist:serialize "method=text media-type=text/plain";

let $document := '/db/apps/exhibit/data/contributors.xml'
(: special characters such as left and right curly brace and newline  :)
let $lcb := '{', $rcb := '}', $nl := '
'
(: json file header and footer as well as item header and footers :)
let $json-header := concat($lcb, $nl, ' "items" : [ ')
let $json-footer := concat($nl, '  ]', $nl,$rcb)
let $item-header := concat($nl, '    ', $lcb, '  ')
let $item-footer := concat('    ', $rcb)
return
<results>{$json-header}
{
   string-join(
      for $contributor in doc($document)/contributors/contributor
      return
<item>{$item-header}label:       "{$contributor/author-name/text()}",
       location:     "{$contributor/location/text()}",
       "image-url":    "{$contributor/image-url/text()}"
{$item-footer}</item>
   , ', ')
}{$json-footer}</results>

JSON 輸出示例

[編輯 | 編輯原始碼]
{
 "items" : [ 
    {  label:        "John Doe",
       location:     "New York, NY",
       "image-url":  "http://www.example.com/images/john-doe.jpg"
    }, 
    {  label:        "Sue Anderson",
       location:     "San Francisco, CA",
       "image-url":  "http://www.example.com/images/sue-anderson.jpg"
    }
  ]
}

替代方法

[編輯 | 編輯原始碼]

另一種方法是使用 XQuery 中可以轉義大括號的事實,方法是將其加倍。由於輸出被序列化為文字,因此所有元素都將被序列化,因此無需單獨序列化專案。

xquery version "1.0";
declare option exist:serialize "method=text media-type=text/plain";
let $document := '/db/Wiki/JSON/contributors.xml'
return

<result>
{{
  "items" : [
{
   string-join(
      for $contributor in doc($document)/contributors/contributor
      return
<item>
       {{
label: "{$contributor/author-name}",
location: "{$contributor/location}",
"image-url":  "{$contributor/image-url}"
       }}
</item>
       , ', '
     )
}
     ]
}}
</result>

執行

華夏公益教科書