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

Time:02-21

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.

CodePudding user response:

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']) }
  )
}

CodePudding user response:

Combining the answers I got in this post, I've made this code which works exactly as needed. Thanks to everyone who chimed in (Christian Grūn)

let $male:=//INHABITANT[@Gender="M"]
let $female:=//INHABITANT[@Gender="F"]
return 
<GENDERS>
<FEMALES>{count($female)}</FEMALES>
<MALES>{count($male)}</MALES>
</GENDERS>
  • Related