Search code examples
xmlxquery

Return a number of how many times an attribute has been used in XML using XQuery


I have an XML file that looks like this:

<CITY>
<STREET>
<HOUSE>
<FLAT>
<INHABITANT Year="1990" Gender="M">John Doe</INHABITANT>
<INHABITANT Year="1990" Gender="F">Jane Doe</INHABITANT>
<INHABITANT Year="1990" Gender="M">John Doe</INHABITANT>
</FLAT>
</HOUSE>
</STREET>
</CITY>

Using XQuery I need to return this:

<GENDERS><FEMALES>1</FEMALES><MALES>2</MALES></GENDERS>

How would I go about doing this? What would the code be for this? As I understand XQuery is for XML what SQL is for databases, so that kind of gives me an idea. This is for a school project that requires XQuery and I have 0 experience with this.


Solution

  • One possible solution is as follows:

    let $doc := document {
       <CITY>
        <STREET>
          <HOUSE>
            <FLAT>
              <INHABITANT Year="1990" Gender="M">John Doe</INHABITANT>
              <INHABITANT Year="1990" Gender="F">Jane Doe</INHABITANT>
              <INHABITANT Year="1990" Gender="M">John Doe</INHABITANT>
            </FLAT>
          </HOUSE>
        </STREET>
      </CITY>
    }
    return element GENDERS {
      let $genders := $doc//INHABITANT/@Gender
      return (
        element FEMALES { count($genders[. = 'F']) },
        element MALES   { count($genders[. = 'M']) }
      )
    }