Domanda

I'm fairly new to XML and XQuery. The XML data that I have looks like:enter image description here

And what I would like to get as a result is:

 <country name="country-name">
      <big>city-name</big>
      <big>city-name</big>
    </country>

My Code is:

for $a in doc("countries.xml")/countries/country[count(city[population > 7000000])>=1]
return 
<country> {$a/@name}
{let $b := $a/city[population>7000000]/name
return <big>{$b}</big>}
</country>

Any hint how can I get the result formatted as above is really appreciated. Thanks

È stato utile?

Soluzione

I guess your problem is you want to omit the <name> tags around the city name. You can do so by adding /data() when using its value, eg.

<big>{$b/data()}</big>

Also, you don't need to count the elements in a predicate. Predicates are existence quantified; so if there is at least one, it is true, otherwise false. Another problem is you did not loop over the cities. A slightly cleaned up version of your code:

for $country in doc("countries.xml")/countries/country[city/population > 7000000]
return 
  <country>{
    $country/@name,
    for $city in $country/city[population > 7000000]
    return <big>{ $city/name/data() }</big>  
  }</country>

By using computed element constructors in axis steps (supported by newer XQuery 3.0 implementations, I tested using BaseX), you can condense the code to even fewer lines:

for $country in doc("countries.xml")/countries/country[city/population > 7000000]
return element country {
    $country/@name,
    $country/city[population > 7000000]/element big { ./name/data() }
  }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top