The reason for a difference between
for $u in doc("lib.xml")//user
for $l in doc("lib.xml")//loan
where $l/@user = $u/id/@val
order by $u/name
return $u/name
and
for $u in doc("lib.xml")//users
for $l in doc("lib.xml")//loans
where $l/loan/@user = $u/user/id/@val
order by $u/user/name
return $u/user/name
...is that only the former iterates over individual user
elements. The second "iterates" over users
elements, of which there are only one, so no actual iteration occurs at all.
When you let $l
point at loans
and use $l/loan/@user
, you're asking if any loan at all contains a match -- without looking with any specificity at which loan matched, because $l
doesn't point to a single loan! Consequently, your return
expression has no way of addressing the specific match, because its $l
doesn't look at an individual matched loan
, but at their joint parent, loans
.
Similarly, for $x at $xPos in doc("lib.xml")//loans
only finds one loans
element; it doesn't look at the loan
elements inside of it, because you aren't telling it to do so.
If you wanted $x
to be a loan
element, not a loans
element, you'd need to either fix it the way you already did, or do this:
for $x at $xPos in doc("lib.xml")//loans/*