I have a doubt with an XQuery code that I've written for a uni proyect. The code is as follows:
<results>
{
for $item in doc("data.xml")//item
return
<country alpha-2="{$item/city/country}">
<name> {doc("countries.xml")//country[@alpha-2=$item/city/country]/@name} </name>
<cities>
<city>
<name> {$item/city/@name} </name>
<temp unit="{$item/temperature/@unit}"> {$item/temperature/@value} </temp>
<feels_like unit="{$item/feels_like/@unit}"> {$item/feels_like/@value} </feels_like>
<humidity unit="{$item/humidity/@unit}"> {$item/humidity/@value} </humidity>
<pressure unit="{$item/pressure/@unit}"> {$item/pressure/@value} </pressure>
<clouds> {$item/clouds/@name} </clouds>
</city>
</cities>
</country>
}
</results>
Which seems pretty straightforward, but when I compile it, the value of the new nodes appear as attributes, as shown on the following code:
<?xml version="1.0" encoding="UTF-8"?>
<results>
<country alpha-2="LV">
<name name="Latvia"/>
<cities>
<city>
<name name="Zilupe"/>
<temp unit="kelvin" value="281.15"/>
<feels_like unit="kelvin" value="277.59"/>
<humidity unit="%" value="86"/>
<pressure unit="hPa" value="1023"/>
<clouds name="overcast clouds"/>
</city>
</cities>
</country>
<country alpha-2="RU">
<name name="Russian Federation"/>
<cities>
<city>
<name name="Sebezh"/>
<temp unit="kelvin" value="280.82"/>
<feels_like unit="kelvin" value="277.37"/>
<humidity unit="%" value="90"/>
<pressure unit="hPa" value="1023"/>
<clouds name="overcast clouds"/>
</city>
</cities>
</country>
</results>
Does anyone know why this is happening? Im probably missing something obvious, but I cannot see it.
Since you are pulling out an attribute in the xpath, then that is what you are placing in the element. You need to surround the xpath with an xs:string()
<name> {doc("countries.xml")//country[@alpha-2=$item/city/country]/@name} </name>
Should be
<name> {xs:string(doc("countries.xml")//country[@alpha-2=$item/city/country]/@name)} </name>