跳至內容

XQuery/XQuery 和 Python

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

[1],Cameron Laird 舉例展示了一個 Python 程式碼,用於從 XHTML 頁面上提取和列出 a 標籤

    import elementtree.ElementTree
    
    for element in  elementtree.ElementTree.parse("draft2.xml").findall("//a"):
        if element.tag == "a":
            attributes = element.attrib
            if "href" in attributes:
                print "'%s' is at URL '%s'." % (element.text,
                                                attributes['href'])
            if "name" in attributes:
                print "'%s' anchors '%s'." % (element.text,
                                                attributes['name'])
        

此 Python 程式碼在 XQuery 中的等效程式碼如下

 for $a in doc("http://en.wikipedia.org/wiki/XQuery")//*:a
 return   
   if ($a/@href)
   then concat("'", $a,"'  is at  URL '",$a/@href,"'
")
   else if ($a/@name)
   then concat("'", $a,"'  anchors '",$a/@name,"'
")
   else ()
        

維基百科 XQuery 中的 tags(檢視原始碼)

此處的名稱空間字首為萬用字元,因為我們不知道 html 名稱空間是什麼。

更簡潔,但可讀性稍低(並且為提高明確性而省略了輸出中的引號),可以表示為

 string-join(
      doc("http://en.wikipedia.org/wiki/XQuery")//*:a/
        (if (@href)
        then concat(.,"  is at  URL ",@href)
        else if (@name)
        then concat(.," anchors ", @name)
        else ()
        )
         ,'
'
     )

維基百科 XQuery 中的 tags(檢視原始碼)

更為實用的是,我們可能會將任何 XHTML 頁面的 url 作為引數提供,並生成一個包含外部連結的 HTML 頁面

declare option exist:serialize "method=xhtml media-type=text/html";

let $url :=request:get-parameter("url",())
return
  <html>
      <h1>External links in {$url}</h1>
       { 
        for $a in doc($url)//*:a[text()][starts-with(@href,'http://')]
        return 
               <div><b>{string($a)}</b> is at  <a href="{$a/@href}"><i>{string($a/@href)}</i> </a></div>
       }
  </html>

維基百科 XQuery

華夏公益教科書