Search code examples
if-statementxquery

XQUERY If Then Else


I have the following xml example, which I'm trying to xquery in BaseX.

<book>     <title>Book 1</title>     <price>15.99</price>   </book>  <book>     <title>Book 2</title>     <price>5.99</price>    </book>   <book>     <title>Book 3</title>     <price>5</price>    </book>

Basically it's a series of elements with a price tag. I'm trying to extract it with a tag to each depending on the price range, so for instance less then 10 would be cheap, then average, then premium.

Thanks in advance.


Solution

  • Here is an example, I assumed there is a books root element around the book elements:

    declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
    
    declare option output:method "xml";
    declare option output:indent "yes";
    
    <categories>
    {
    for $book in books/book
    group by $cat := if ($book/price < 10) then 'cheap' else if ($book/price < 20) then 'average' else 'premium'
    return
      <category name="{$cat}">{$book}</category>  
    }
    </categories>
    

    Output is e.g.

    <categories>
       <category name="average">
          <book>
             <title>Book 1</title>
             <price>15.99</price>
          </book>
       </category>
       <category name="cheap">
          <book>
             <title>Book 2</title>
             <price>5.99</price>
          </book>
          <book>
             <title>Book 3</title>
             <price>5</price>
          </book>
       </category>
    </categories>