使用XQuery获取常见元素

时间:2016-09-05 02:04:54

标签: xml xpath xquery

我遇到了使用XQuery返回基于标记的公共元素的问题。我正在尝试编写一个返回公共元素的XQ函数。例如,我有一个XML: $ schoolA

<schoolA>
    <name>ABC</name>
    <students>1000</students>
    <classes>25</classes>
</schoolA>
<schoolA>
    <name>DEF</name>
    <students>1200</students>
    <classes>20</classes>
</schoolA>
<schoolA>
    <name>GHY</name>
    <students>900</students>
    <classes>30</classes>
</schoolA>

另一个: $ schoolB

<schoolB>
    <name>ABC</name>
    <students>1000</students>
    <classes>25</classes>
</schoolB>
<schoolB>
    <name>DEF</name>
    <students>1200</students>
    <classes>20</classes>
</schoolB>
<schoolB>
    <name>XYZ</name>
    <students>1100</students>
    <classes>30</classes>
</schoolB>

该函数应返回: $ commonSchool

<schoolA>
    <name>ABC</name>
    <students>1000</students>
    <classes>25</classes>
</schoolA>
<schoolA>
    <name>DEF</name>
    <students>1200</students>
    <classes>20</classes>
</schoolA>

匹配因子是名称。我试图编写一个嵌套的for循环,但卡住将该元素附加到变量。关于如何做到这一点的任何线索都会很棒!

1 个答案:

答案 0 :(得分:1)

此XQuery函数根据<name>元素的值匹配两个元素序列。简单的假设是您将两组School元素包装在名为<schools>的包装中。

这适用于XQuery 1.0。

declare namespace _="http://local/funcs";

declare function _:munge($schoolA as element()*, $schoolB as element()*) {
    $schoolA[name=$schoolB/name]
};

_:munge(schools/schoolA, schools/schoolB)