XQuery - 为什么$ x in // loan与$ x in //贷款和使用$ x / loan不同?

时间:2014-03-29 21:21:32

标签: xml xquery

我有一个xml文件。

<?xml version = "1.0" encoding = "UTF -8"?>
<library>
<books>
    <book>
        <title>The story of My Life</title>
        <accessionNumber val = "1"/>
    </book>
    <book>
        <title>The Parody</title>
        <accessionNumber val = "2"/>
    </book>
    <book>
        <title>The Automata Theory</title>
        <accessionNumber val = "3"/>
    </book>
</books>
<loans>
    <loan book="1" user="35" dueDate="2006-April-10-05:00"/>
    <loan book="2" user="36" dueDate="2015-May-10-05:00"/>
    <loan book="3" user="36" dueDate="2014-November-10-05:00"/>
</loans>
<users>
    <user> <name> Fred Jones</name> <id val = "35"/> </user>
    <user> <name> Aadeem Nus</name> <id val = "36"/> </user>
</users>

我必须找到(a)按用户名

排序的所有贷款清单

(b)用户借了多本书

我的解决方案(a)我已经解决了。解决的xquery是:

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

但这需要很长时间,因为我正在尝试

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

我认为它们之间没有区别。有什么区别?

(b)与(a)相同的问题。很久以后我解决了。解决了一个:

for $u_n in doc("lib.xml")//user 
for $x at $xPos in doc("lib.xml")//loan
for $y at $yPos in doc("lib.xml")//loan
where $x/@user = $y/@user
and $xPos < $yPos
and $u_n/id/@val = $x/@user
return data($u_n/name)

未解决的问题(与我解决的问题相同):

for $u_n in doc("lib.xml")//user 
for $x at $xPos in doc("lib.xml")//loans
for $y at $yPos in doc("lib.xml")//loans
where $x/loan/@user = $y/loan/@user
and $xPos < $yPos
and $u_n/id/@val = $x/loan/@user
return data($u_n/name)

有人可以解释一下吗?

感谢。

1 个答案:

答案 0 :(得分:1)

之间存在差异的原因
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

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

...只有前者迭代单个user元素。第二个&#34;迭代&#34;超过users个元素,其中只有一个元素,因此根本不会发生实际的迭代。

当您$l指向loans并使用$l/loan/@user时,您就会问任何贷款是否包含匹配项 - 没有因为$l没有指向一笔贷款,所以哪个贷款匹配时具有任何特异性!因此,您的return表达式无法解决特定匹配,因为$l并未查看匹配的loan个体,而是在其共同父级{{1} }}


同样,loans只找到一个for $x at $xPos in doc("lib.xml")//loans元素;它没有查看其中的loans元素,因为你没有告诉它这样做。

如果您希望loan成为$x元素,而不是loan元素,则需要按照您现有的方式修复它,或者执行以下操作:

loans