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

Trying to perform a cartesian product on two XML files using XQuery

我正在尝试使用 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>