I am getting my desired schema. But the one thing i need to do is to eliminate duplicate values. Hence I use distinct values, but what that function does is it displays all the values within one element.
Input Schema:
<?xml version="1.0" encoding="UTF-8"?>
<hotel>
<food>
<name>Burger</name>
<cost>20</cost>
</food>
<food>
<name>Pizza</name>
<cost>20</cost>
</food>
<food>
<name>Cola</name>
<cost>5</cost>
</food>
<food>
<name>Lemonade</name>
<cost>5</cost>
</food>
<food>
<name>Ice Cream</name>
<cost>10</cost>
</food>
<food>
<name>Cookies</name>
<cost>10</cost>
</food>
</hotel>
Output presently:
<type>
<cost>01</cost>
<food>burger fries cola</food>
</type>
Desired:
<type>
<cost>01</cost>
<food>burger</food>
<food>fries</food>
<food>cola</food>
</type>
Basically get all the food for that price.
My Xquery is as follows:
let $cost:= doc("Untitled7.xml")/hotel/food/cost
for $unique in distinct-values(doc("Untitled7.xml")/hotel/food/cost)
let $food:= distinct-values(doc("Untitled7.xml")hotel/food[cost=$unique]/name)
where $unique = $cost
return
<type>
<year>{$unique}</year>
<food>{$food}</food>
</type>
Any help will be appreciated :)
We can use distinct-values function which is available in XPath 2.0 for finding the unique values. The fn:distinct-values function returns a sequence of unique atomic values from $arg . Values are compared based on their typed value.
Distinct values are all different items in a list, i.e. unique values and 1st occurrences of duplicate values.
distinct-values() will return a sequence of strings: ('burger', 'fries', 'cola'), but right now you're outputting it at once. What you need to do is iterate over your $food variable in another FLWOR statement:
return
<type>
<year>{$unique}</year>
{
for $f in $food return <food>{$f}</food>
}
</type>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With