我对XQuery很新,并且知道这可能是一个简单的答案,但我无法绕过这个问题。
我有一个像这样的XML文件:
<EventLog>
<SongSet>
<Song SongID="S002">
<Title>Band on the Run</Title>
<Composer>Paul McCartney</Composer>
<Duration>1.15</Duration>
</Song>
<Song SongID="S003">
<Title>Come on Over</Title>
<Composer>Shania Twain</Composer>
<Duration>3.15</Duration>
</Song>
</SongSet>
<ContestantSet>
<Contestant Name="Randy Stuss" Hometown="Ottawa">
<Repertoire>
<SongRef>S002</SongRef>
<SongRef>S003</SongRef>
</Repertoire>
</Contestant>
<Contestant Name="Fletcher Gee" Hometown="Toronto">
<Repertoire>
<SongRef>S002</SongRef>
<SongRef>S003</SongRef>
</Repertoire>
</Contestant>
</ContestantSet>
</EventLog>
我需要输出看起来像这样:
<songs>
<song>
<name> SONG NAME1 </name>
<composer> COMPOSER NAME </composer>
<singers>
<singer>Singer1 Name </singer>
<singer>Singer2 Name </singer>
</singers>
</song>
<songs>
除了将歌手的名字放在一起之外,我可以做所有这些。我的输出如下:
<Songs
<Song>
<Title>Band on the Run</Title>
<Composer>Paul McCartney</Composer>
<Singers>
<Singer>Fletcher Gee</Singer>
</Singers>
</Song>
<Song>
<Title>Band on the Run</Title>
<Composer>Paul McCartney</Composer>
<Singers>
<Singer>Randy Stuss</Singer>
</Singers>
</Song>
</Songs>
这是我的XQuery代码:
for $x in //SongSet/Song
for $y in //ContestantSet/Contestant
where $x/@SongID = $y/Repertoire/SongRef
return <Song><Title>{data($x/Title)}</Title>
<Composer>{data($x/Composer)}</Composer>
<Singers><Singer>{data($y/@Name)}</Singer></Singers></Song>
我哪里错了?
感谢您的帮助!!!!
答案 0 :(得分:1)
一种可能的方式;循环遍历<Song>
元素,然后遍历匹配的return <Singers>
元素上的<Contestant>
部分循环:
for $x in //SongSet/Song
return <Song><Title>{data($x/Title)}</Title>
<Composer>{data($x/Composer)}</Composer>
<Singers>{for $y in //ContestantSet/Contestant[Repertoire/SongRef = $x/@SongID]
return <Singer>{data($y/@Name)}</Singer>}</Singers></Song>
<强> Xpathtester Demo
强>
在对相关XML进行测试时,输出符合预期:
<?xml version="1.0" encoding="UTF-8"?>
<Song>
<Title>Band on the Run</Title>
<Composer>Paul McCartney</Composer>
<Singers>
<Singer>Randy Stuss</Singer>
<Singer>Fletcher Gee</Singer>
</Singers>
</Song>
<Song>
<Title>Come on Over</Title>
<Composer>Shania Twain</Composer>
<Singers>
<Singer>Randy Stuss</Singer>
<Singer>Fletcher Gee</Singer>
</Singers>
</Song>