XQuery: Creating Document with Processing Instruction

Today I stumped on how to create a XML document, storing it in a XQuery variable, that is composed from both a processing instruction and an XML body.

While this might seem easy at first, creating the document as once:

let $xml := <?xml-stylesheet href="common.css"?><foo>bar</foo>

The truth is that this does not work. Nevertheless, there is a set of ways to construct documents on XQuery. One of them, that looks really powerful, is the computed constructors. While this recommendation does not have many examples, this other page from Altova might be useful to visualize how to use them.

After banging with the head for some time, with this solution:

let $pi = <?xml-stylesheet href="common.css"?>
let $xml = <foo>bar</foo>
return document {($pi,$xml)}

This were still not working. Or, in other words, they were working, but eXide, the Web IDE for eXist-DB, was misbehaving. Instead of presenting the full document, it was only showing the processing instruction. But when trying this block of code on the function I was preparing, it worked like a charm.

Thanks to Joe Wicentowski for pointing me in the computed constructors documentation.