0
votes

I am stuck with a problem using XQuery to return common elements based on a tag. I am trying to write a XQ function which returns the common elements. For example I have an XML as: $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>

The other one as: $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>

The function should return: $commonSchool

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

The matching factor is the name. I am trying to write a nested for loop, but stuck appending the element to a variable. Any clues on how to do it would be great!

1
Questions asking for homework help must include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it. See stackoverflow.com/help/on-topic. - Joe Wicentowski
XQuery 1.0 or 3.0/3.1? In 3.0/3.1 you can use the new "group by" construct. - Michael Kay

1 Answers

1
votes

This XQuery function matches two sequences of elements based on the value of the <name> element. Assumption for simplicity is that you have wrapped your two sets of School elements in a wrapper called <schools>.

This works with 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)