Thursday, 20 May 2010

MarkLogic: XQuery - Notes on Return Types

Here are some brief notes and examples of specific return types in XQuery:


local:gen-string returns an xs:string. Not that uncommon, although I include this example here to demonstrate another way to concatenate in XQuery; this is something I often use with xdmp:log statements:


Functions which write elements and attributes can be tasked to return those specific types, like so:

However, as elements and attributes are nodes, it's also possible to make a function which returns a node(). This example will return an element containing one attribute:

In the above example, you could also return the content as an element(), but there are definite places where returning an element can be very useful. This example demonstrates a function which returns an element with a given name (which I've rather unimaginatively named 'blah' for this example).

Such an example may be useful for situations where you really want to be specific about the kind of content a function can return:

Example usage:

Finally, here's an example of a function which returns another specific type of node: a document-node() representing a document which is stored in the database:

Example usage:

3 comments:

Rob said...

Hi Alex,

It's also worth noting that if you make the mistake of returning a different type to that specified by the function, ML will try to coerce it into that type. Normally it will error, but sometimes it won't..

e.g.

xquery version '1.0-ml';

declare function local:test() as xs:string
{
<x attr="1">blah</x>
};

local:test()
(: returns string "blah" :)


Caught me out a while back when upgrading some old code.

Regards,
Rob
(xqueryhacker.com)

Alex Bleasdale said...

Very useful to know Rob; thanks for sharing!

Sophia Heath said...

The Double spark team is very professional and shows that this can be a high-class business in which you get the help for what you're paying for. The developers and also the best seo in Cambridge group really helped my sister together with her website and SEO for her baking company where she is being contacted by many new clients.
best seo in cambridge