XQuery数据分组(将一对一转换为一对多)



我有一个一对一关系的XML元素结构,如下所示:

<CrewAllocation>
<Crew>Crew A</Crew>
<CrewMember>John Smith</CrewMember>
</CrewAllocation>
<CrewAllocation>
<Crew>Crew A</Crew>
<CrewMember>Jack Jones</CrewMember>
</CrewAllocation>
<CrewAllocation>
<Crew>Crew B</Crew>
<CrewMember>John Johnson</CrewMember>
</CrewAllocation>

我想把它转换成:

<CrewAllocation>
<Crew>Crew A</Crew>
<CrewMembers>
<CrewMember>John Smith</CrewMember>
<CrewMember>Jack Jones</CrewMember>
</CrewMembers>
</CrewAllocation>
<CrewAllocation>
<Crew>Crew B</Crew>
<CrewMembers>
<CrewMember>John Johnson</CrewMember>
</CrewMembers>
</CrewAllocation>

在XQuery中有一种简单的方法可以做到这一点吗?或者也许是一种更好的提问方式:在XQuery中,什么是最有效的方法?

谢谢!

这里是BaseX v.9.4.4的实现。

此外,我必须通过添加根标记使输入XML格式良好。

XQuery

xquery version "3.1";

declare context item := document {
<root>
<CrewAllocation>
<Crew>Crew A</Crew>
<CrewMember>John Smith</CrewMember>
</CrewAllocation>
<CrewAllocation>
<Crew>Crew A</Crew>
<CrewMember>Jack Jones</CrewMember>
</CrewAllocation>
<CrewAllocation>
<Crew>Crew B</Crew>
<CrewMember>John Johnson</CrewMember>
</CrewAllocation>
</root>
};
<root>
{
for $x in ./root/CrewAllocation
let $crew := $x/Crew
group by $crew
order by $crew
return <CrewAllocation>
<Crew>{$crew}</Crew>
<CrewMembers>{$x/CrewMember}</CrewMembers>
</CrewAllocation>
}
</root>

输出

<root>
<CrewAllocation>
<Crew>Crew A</Crew>
<CrewMembers>
<CrewMember>John Smith</CrewMember>
<CrewMember>Jack Jones</CrewMember>
</CrewMembers>
</CrewAllocation>
<CrewAllocation>
<Crew>Crew B</Crew>
<CrewMembers>
<CrewMember>John Johnson</CrewMember>
</CrewMembers>
</CrewAllocation>
</root>

最新更新