首先,是的,這是家庭作業 - 請建議我去哪裏錯了,但請不要爲我做我的作業。如何在使用XQuery提供ID時查找歌曲的持續時間?
我正在學習XQuery,我的一項任務是獲取歌曲ID的列表以確定演奏的總時間長度。鑑於下面的小竅門,任何人都可以指出我在哪裏可以確定如何交叉參考歌曲ID從演奏到歌曲的持續時間?
我在問題的最後列出了我的嘗試。
我當前的XQuery代碼如下所示:
let $songIDs := doc("C:/Users/rob/Downloads/A4_FLOWR.xml")
//SongSet/Song
for $performance in doc("C:/Users/rob/Downloads/A4_FLOWR.xml")
//ContestantSet/Contestant/Performance
return if($performance/SongRef[. =$songIDs/@SongID])
then <performanceDuration>{
data($performance/SongRef)
}</performanceDuration>
else()
,輸出:
<performanceDuration>S005 S003 S004</performanceDuration>
<performanceDuration>S001 S007 S002</performanceDuration>
<performanceDuration>S008 S009 S006</performanceDuration>
<performanceDuration>S002 S004 S007</performanceDuration>
每個S00x是一首歌曲,其中我們引用的XML文檔(部分文檔)中發現的ID:
<SongSet>
<Song SongID="S001">
<Title>Bah Bah Black Sheep</Title>
<Composer>Mother Goose</Composer>
<Duration>2.99</Duration>
</Song>
<Song SongID="S005">
<Title>Thank You Baby</Title>
<Composer>Shania Twain</Composer>
<Duration>3.02</Duration>
</Song>
</SongSet>
性能部分看起來像:
次<Contestant Name="Fletcher Gee" Hometown="Toronto">
<Repertoire>
<SongRef>S001</SongRef>
<SongRef>S002</SongRef>
<SongRef>S007</SongRef>
<SongRef>S010</SongRef>
</Repertoire>
<Performance>
<SongRef>S001</SongRef>
<SongRef>S007</SongRef>
<SongRef>S002</SongRef>
</Performance>
</Contestant>
我嘗試
我想我會使用嵌套循環,但失敗:
let $songs := doc("C:/Users/rob/Downloads/A4_FLOWR.xml")
//SongSet/Song
for $performance in doc("C:/Users/rob/Downloads/A4_FLOWR.xml")
//ContestantSet/Contestant/Performance
return if($performance/SongRef[. =$songs/@SongID])
for $song in $songIDs
(: gives an error in BaseX about incomplete if :)
then <performanceDuration>{
data($performance/SongRef)
}</performanceDuration>
else()
- 編輯 -
我固定的內環,然而,我得到的所有歌曲的持續時間,不只是那些匹配ID的。我有一種感覺,這是由於變量的作用域,但我不知道:
let $songs := doc("C:/Users/rob/Downloads/A4_FLOWR.xml")//SongSet/Song
for $performance in doc("C:/Users/rob/Downloads/A4_FLOWR.xml")//ContestantSet/Contestant/Performance
return if($performance/SongRef[. =$songs/@SongID])
then <performanceDuration>{
for $song in $songs
return if($performance/SongRef[. =$songs/@SongID])
then
sum($song/Duration)
else()
}</performanceDuration>
else()
}
輸出:
<performanceDuration>2.99 1.15 3.15 2.2 3.02 2.25 3.45 1.29 2.33 3.1</performanceDuration>