跳轉到內容

XQuery/多頁抓取和投票行為

來自華夏公益教科書

通常,所需資料分散在多個網頁上。

以下是一個從多個頁面獲取資料以收集美國眾議院成員投票行為的示例。

任何一屆眾議院的議題索引由諸如 [1] 的頁面提供。在這裡,可以看出,報告任何連續編號投票的頁面是由諸如 [2] 的查詢生成的。

結果以 XML 頁面形式返回,該頁面使用 XSLT 在瀏覽器中呈現。XQuery doc() 函式檢索底層 XML。

以下查詢彙總了特定成員在 6 次特定投票中的投票行為。

<results>
{for $i in 10 to 15
let $path := concat("http://clerk.house.gov/evs/2007/roll0",$i,".xml")
let $report := doc($path)
let $bill := $report//vote-metadata
let $specificvote := $report//recorded-vote[legislator/@name-id = "E000215"]
let $result := concat(data($specificvote//legislator)," voted ",data($specificvote/vote)," ",data($bill/vote-question)," of ",data($bill//legis-num))
return
  <result>{$result}</result>
}
</results>

執行

更一般地說,以下函式將返回包含提取資料的 XML 節點。通常,投票頁面使用前導零對投票編號進行編碼,最小長度為 3 位數字。

declare function local:voting($repid as xs:string, $year as xs:integer, $rollnumbers as xs:integer*) {
for $rollno in $rollnumbers
let $zeropaddedrollnum  := concat(string-pad("0",max((0,3 - string-length(xs:string($rollno))))),xs:string($rollno))
let $path := concat("http://clerk.house.gov/evs/",$year,"/roll",$zeropaddedrollnum,".xml")
let $report := doc($path)
let $bill := $report//vote-metadata
let $specificvote := $report//recorded-vote[legislator/@name-id = $repid]
return
  <result>
     <year>{$year}</year>
     {$bill/rollcall-num}
     {$bill/vote-question}
     {$bill/legis-num}
     {$specificvote/legislator}
     {$specificvote/vote}
 
  </result>
};

<report>
  {local:voting("E000215",2007,10 to 15)}
</report>

執行


注意:最好使用 asp 終結點,因為這不會涉及此處因前導零而產生的複雜情況,但這會產生格式錯誤的 XML(??)。

華夏公益教科書