What is a context item type? And how do I set it?

You might wonder why you get the following error when running a simple XQuery, like Hello, for example, using DataDirect XQuery™:

The context item static type has not been set

Most likely what you are trying to do is to write an XQuery that returns the character string "Hello"; but the way that XQuery is written means: return all children elements of the context item whose name matches "Hello". The correct XQuery is:

"Hello"

The reported error is actually an XQuery compilation error, not even a runtime one; what's happening here is that DataDirect XQuery™ is not finding information about the type for the context item (it's not complaining about the lack of data yet). If you are using the DataDirect XQuery™ command line, no information (type or data) about the context item is specified by it unless you provide the –s option. If you use the DataDirect XQuery™ XQJ implementation, you can set the context item type by doing the following:

   XQStaticContext cntxt = xqConnection.getStaticContext();
   cntxt.setContextItemStaticType(xqConnection.createDocumentElementType(xqConnection.createElementType(null, XQItemType.XQBASETYPE_UNTYPED)));

... for example (assuming you are planning to bind a generic document to the context item).

If you specify the static type for the context item, but you bind no value for it, you will get a different error trying to run the XQuery described at the beginning of this section:

Error XPDY0002: The context item for axis step child::element(Hello) is undefined;

To both set the static type and bind a document to the context item, you can do:

   XQStaticContext cntxt = xqConnection.getStaticContext();
   cntxt.setContextItemStaticType(xqConnection.createDocumentElementType(xqConnection.createElementType(null, XQItemType.XQBASETYPE_UNTYPED)));
   xqExpression = xqConnection.createExpression(cntxt);
   xqExpression.bindDocument(XQConstants.CONTEXT_ITEM, new FileInputStream("myDocument.xml"));

There are of course different ways to reference the XML document to be bound, including StAX or SAX streams and DOM trees.


Next Question!

Can I include CDATA sections in my XQuery results?

Submit Your DataDirect XQuery Tip or Trick

Tell us your XQuery Tip or Trick – if it gets published on our site, you’ll receive a

$10.00 Amazon.com
Gift Certificate!

Submit your tip or trick today.