You may prefer to move the query from the where
clause into a separate function, but this should work:
<Courses>{
for $co in doc('data.xml')//Course
let $code := $co/@CrsCode
for $class in doc('data.xml')//Class[CrsCode = $code]
let $sem := $class/Semester
where exists(doc('data.xml')//Student/CrsTaken[@CrsCode = $code and @Semester = $sem])
return <course CrsCode="{ $co/@CrsCode }" name="{ $co/CrsName }" />
}</Courses>
Generally, exists()
should perform better than counting all of the students because the XQuery processor should stop counting after 1; however, this will not have much impact unless that data set is much larger.
Also, a note about text()
(and data()
): typically string()
is what you want, and in many cases (like this example) values will be coerced into strings automatically. For more information, Evan Lenz has a very good blog on the topic: