stefan.kenyon
stefan.kenyon

Reputation: 339

XML XQuery Multiple Child Elements

I need to find a way to see whether parent element has more than one child element using XQuery

let $d:=doc("/Users/stefan.kenyon/company.xml")
for $e in $d/companyDB/employees/employee[dependents]
return $e/lname

That is my query, and it returns all employees with dependents.

What I need help with is how to sort the employees by how many dependents they have. So the modified query will return

Employee #1

<dependent>
      <dependentName>Michael</dependentName>
      <sex>M</sex>
      <dob>01-JAN-1978</dob>
      <relationship>Son</relationship>
    </dependent>
    <dependent>
      <dependentName>Alice</dependentName>
      <sex>F</sex>
      <dob>31-DEC-1978</dob>
      <relationship>Daughter</relationship>
    </dependent>
<dependent>

Who has two dependents,

But NOT return

Employee #2

<dependents>
    <dependent>
      <dependentName>Johnny</dependentName>
      <sex>M</sex>
      <dob>04-APR-1997</dob>
      <relationship>Son</relationship>
    </dependent>
<dependent>

Who only has one dependent.

Thanks.

Upvotes: 0

Views: 796

Answers (1)

Michael Kay
Michael Kay

Reputation: 163262

Neither of your input samples is well-formed XML, so we have to do some guesswork. But the simplest way to test whether there are two or more dependents is to test whether dependent[2] exists, which gives you something like:

for $e in $d/companyDB/employees/employee[dependents/dependent[2]]

If you prefer something more readable, you might prefer

for $e in $d/companyDB/employees/employee[count(dependents/dependent) ge 2]

Upvotes: 1

Related Questions