尝试使用XQuery对两个XML文件执行笛卡尔积



我正在尝试使用XML数据集,并且我很难理解如何使用XQuery执行迭代和连接操作。

我有这两个XML表:

employees.xml:

<employees>

<employee cod="E01" dept="D01">
<name>John</name>
<middle-name>S.</middle-name>
<lastname>Gladstone</lastname>
</employee>

<employee cod="E02" dept="D01">
<name>Ana</name>
<lastname>Ferraz</lastname>
</employee>
</employees>

和departments.xml:

<departments>
<department cod="D01">
<name>Sales</name>
<local>3rd floor</local>
</department>

<department cod="D02">
<name>Finances</name>
<local>4th floor</local>
</department>

</departments>

我想对这些数据执行连接操作,结果如下:

<result>
<dep-emp>
<department>Sales</department>
<employee>John</employee>
</dep-emp>

<dep-emp>
<department>Sales</department>
<employee>Ana</employee>
</dep-emp>

<dep-emp>
<department>Finances</department>
<employee>John</employee>
</dep-emp>

<dep-emp>
<department>Finances</department>
<employee>Ana</employee>
</dep-emp>
</result>

我尝试使用"for"声明没有成功。有人能帮帮我吗?

这是一个非常直接的嵌入式循环:

xquery version "3.0";
let $employees := <employees>
<employee cod="E01" dept="D01">
<name>John</name>
<middle-name>S.</middle-name>
<lastname>Gladstone</lastname>
</employee>
<employee cod="E02" dept="D01">
<name>Ana</name>
<lastname>Ferraz</lastname>
</employee>
</employees>
let $departments := <departments>
<department cod="D01">
<name>Sales</name>
<local>3rd floor</local>
</department>

<department cod="D02">
<name>Finances</name>
<local>4th floor</local>
</department>
</departments>
return <result>{
for $dep in $departments/department
for $emp in $employees/employee[@dept eq $dep/@cod]
return <dep-emp>
<department>{string($dep/name)}</department>
<employee>{string($emp/name)}</employee>
</dep-emp>
}</result>

最新更新