Question

I have an external variable coming in as a string and I would like to do a switch/case on it. How do I do that in xquery?

Was it helpful?

Solution

Starting with XQuery 1.1, use switch:

http://www.w3.org/TR/xquery-11/#id-switch

switch ($animal) 
   case "Cow" return "Moo"
   case "Cat" return "Meow"
   case "Duck" return "Quack"
   default return "What's that odd noise?" 

OTHER TIPS

Just use a series of if expressions:

if ($room eq "bathroom") then "loo"
else if ($room eq "kitchen")  then "scullery"
else "just a room"

Using a typeswitch is hiding what you are really doing.

Which of these methods is most efficient will depend on the XQuery processor you are using. In an ideal world it should only be a matter of taste, as it should be down to the optimizer to select the appropriate method, but if performance is important it is worth benchmarking both versions. I would be very surprised if a processor optimized the node construction out of your example, and didn't optimize my example to a specialized switch.

XQuery doesn't have a function for switching on anything other than elements.

The first thing you do is convert your string to an element.

let $str := "kitchen"
let $room := element {$str} {}

Then just use typeswitch to do a normal switch:

return typeswitch($room)
  case element(bathroom) return "loo"
  case element(kitchen) return "scullery"
  default return "just a room"

Please note, this may be a MarkLogic only solution.

If your processor supports XQuery 1.1, then you can simply do:

switch ($room) 
  case "bathroom" return "loo"
  case "kitchen" return "scullery"
  default return "just a room"

For Saxon, you can use something like this:

declare function a:fn($i) {
typeswitch ($i)
 case element(a:elemen1, xs:untyped) return 'a' 
 case element(a:elemen2, xs:untyped) return 'b' 
 default return "error;"
};

Regards,

http://rrusin.blogspot.com/2010/01/embedding-xquery-in-java.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top