You can use the XQueryExecutable instances that are created
using XFactory.prepareXQuery methods to evaluate XQuery expressions.
About this task
XQuery expressions can be passed to the XFactory.prepareXQuery
method using a JAXP StreamSource object or using a plain Java string object. The resulting XQueryExecutable
instance is thread safe and can be reused to evaluate an XQuery expression
on multiple XML input documents.
Procedure
- Use the XStaticContext object with the prepareXQuery method
to pass in settings that affect how the XQuery expression is prepared.
If no XStaticContext object is provided, the default setting
is used.
XStaticContext settings relevant to XQuery: - declareFunction
- Declare a Java extension
function
- declareNamespace
- Declare a namespace prefix and associate it with a namespace URI
to be used as part of an XQuery expression
- declareVariable
- Declare a variable externally to be used as part of an XQuery
expression
- setBaseURI
- Set the base URI used in the resolution of relative URIs (such
as by the fn:resolve-uri function)
The default is the base URI of
the expression, query, or stylesheet if the base URI is available.
If the base URI is not available, the current working directory is
used.
- setBoundarySpacePolicy
- Specify whether to preserve or strip white space
The options
are as follows:
- BOUNDARY_SPACE_STRIP (default)
- BOUNDARY_SPACE_PRESERVE
- setConstructionMode
- Specify whether to preserve the type of element and attribute
nodes or strip them
The options are as follows:
- CONSTRUCTION_MODE_PRESERVE (default)
- CONSTRUCTION_MODE_STRIP
- setCopyNamespacesModeInherit
- Specify whether to inherit or ignore the namespace when copying
element nodes
The options are as follows:
- COPY_NAMESPACES_MODE_INHERIT (default)
- COPY_NAMESPACES_MODE_NO_INHERIT
- setCopyNamespacesModePreserve
- Specify whether to preserve or strip the namespace when copying
element nodes
The options are as follows:
- COPY_NAMESPACES_MODE_PRESERVE (default)
- COPY_NAMESPACES_MODE_NO_PRESERVE
- setDefaultCollation
- Set the default collation URI for string comparison operations
The
default is the Unicode code point collation URI.
- setDefaultElementTypeNamespace
- Specify the URI of the default element or type namespace
Use
an empty string to make it unspecified.
The default is an empty
string.
- setDefaultFunctionNamespace
- Specify the URI of the default function namespace
Use an empty
string to make it unspecified.
The default is "http://www.w3.org/2005/xpath-functions".
- setDefaultOrderForEmptySequences
- Set the behavior for default order on empty sequences to greatest
or least
The options are as follows:
- DEFAULT_ORDER_FOR_EMPTY_SEQUENCES_LEAST (default)
- DEFAULT_ORDER_FOR_EMPTY_SEQUENCES_GREATEST
- setIntegerMathMode
- Set the integer math mode to one of the following:
- INTEGER_MATH_MODE_LIMITED_PRECISION
- Limit to 18-digit precision for xs:integer (default)
- INTEGER_MATH_MODE_ARBITRARY_PRECISION
- Allow users to have arbitrary precision for xs:integer
- INTEGER_MATH_MODE_OVERFLOW_DETECTION
- Generate an error if an overflow is detected
- setMessageHandler()
- Set the message handler for prepare-time errors
The default
behavior is to print errors, warnings, and informational messages
to System.err and to generate an XProcessException in the case of
an unrecoverable error when compilation cannot continue. If the message
handler that is registered does not generate its own exception in
the case of an unrecoverable error, an XProcessException occurs.
- setModuleResolver
- Set the module resolver used for module imports
The default
module resolution behavior is to attempt to locate one module for
each location hint specified in the module import. The default resolution
behavior for each location hint is to resolve relative URIs against
the base URI from the static context, if the base URI is available,
or to interpret them as file paths relative to the current working
directory, if the base URI is not available. Absolute URIs are used
unchanged. If a module cannot be located for a location hint, the
processor ignores it unless no modules can be loaded for the namespace,
in which case the processor emits an error message.
- setOrderingMode
- Specify whether the results returned by certain path expressions,
union, intersect, and except expressions as well as FLWOR expressions
that have no order by clause are ordered or unordered
The options
are as follows:
- ORDERING_MODE_ORDERED (default)
- ORDERING_MODE_UNORDERED
- setUseCompiler
- Indicate whether to generate a compiled executable or an interpreted
executable
A compiled executable takes longer to generate but runs
faster than an interpreted executable.
The default is interpreted.
- Provide an XDynamicContext object that can be used to pass
settings to the XQueryExecutable.execute method.
These
settings affect the behavior during the execution when the processor
is evaluating an XQuery expression.
If no XDynamicContext object
is provided, the default setting is used.
XDynamicContext
settings relevant to XQuery:- bind
- Bind a value to an external variable
- bindCollation
- Binds an instance of the java.text.Collator class to a particular
collation URI for use in string comparisons that use that collation
URI
- bindFunction
- Bind an external function so that it can be used as part of an
XQuery expression
- bindSequence
- Bind a sequence value to an external variable
- setCollectionResolver
- Set the collection resolver used to resolve documents loaded with
the XPath fn:collection function
The default behavior is for references
to the fn:collection function to return an empty sequence.
- setImplicitTimeZone
- Set the implicit time zone
The default is to use the system
time zone as retrieved through the Java method
java.util.TimeZone.getDefault().
- setMessageHandler()
- Set the message handler for execution-time errors
The default
behavior is to print errors, warnings and informational messages to
System.err and to generate an XProcessException in the case of an
unrecoverable error. If the message handler that is registered does
not generate its own exception in the case of an unrecoverable error,
an XProcessException occurs.
- setSourceResolver
- Set the source resolver used to resolve documents loaded with
the XPath fn:doc function
The default behavior is to resolve documents
based on the base URI from the static context. If the base URI is
not available, the current working directory is used.
- Execute XQuery expressions with schema awareness.
To
validate the input XML files with XQuery, schema files can be registered
using the XFactory.registerSchema() method or users can declare the
xsi:schemaLocation directive in their input XML files. In either case
validation needs to be enabled using the XFactory.setValidating()
method. XQuery only supports validating the input XML file for now.
Example
The following is a basic example of preparing and executing
an interpreted XQuery expression.
// Create a string for the XQuery expression
String expression = "/doc/name[@first='David']";
// Create the factory
XFactory factory = XFactory.newInstance();
// Create the XQueryExecutable
XQueryExecutable xQueryExecutable = factory.prepareXQuery(expression);
// Create the input XML source
String xml = "<doc<name first='John'>Wrong</name><name first='David'>Correct</name></doc>";
// Execute the expression and store the results in an XSequenceCursor
XSequenceCursor xSequenceCursor = xQueryExecutable.execute(new StreamSource(new ByteArrayInputStream(xml.getBytes())));
The
following is a basic example of preparing and executing a compiled
XQuery expression.
// Create a string for the XQuery expression
String expression = "/doc/name[@first='David']";
// Create the factory
XFactory factory = XFactory.newInstance();
// Create a new static context from the factory
XStaticContext xStaticContext = factory.newStaticContext();
// Set the mode to compile for the processor
xStaticContext.setUseCompiler(true);
// Create the XQueryExecutable
XQueryExecutable xQueryExecutable = factory.prepareXQuery(expression, xStaticContext);
// Create the input XML source
String xml = "<doc><name first='John'>Wrong</name><name first='David'>Correct</name></doc>";
// Execute the expression and store the results in an XSequenceCursor
XSequenceCursor xSequenceCursor = xQueryExecutable.execute(new StreamSource(new ByteArrayInputStream(xml.getBytes())));
The
following is a basic example of preparing and executing interpreted
XQuery expressions with schema awareness.
// Create a string for the XQuery expression
String expression = "/my:doc/name[@first='David']/@first";
// Create the factory
XFactory factory = XFactory.newInstance();
// Create the schema source
String schema = "<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'" +
" targetNamespace='http://www.schematype.ibm.com/UDSimple'" +
" xmlns:my='http://www.schematype.ibm.com/UDSimple'" +
" xmlns:smokey='http://www.schematype.ibm.com/UDSimple'>"
+" <xsd:element name='doc'>"
+ "<xsd:complexType> "
+ "<xsd:sequence>"
+ "<xsd:element name='name' minOccurs='0' maxOccurs='unbounded'>"
+ "<xsd:complexType>"
+ "<xsd:attribute name='first' type='xsd:string' use='optional'/>"
+ "</xsd:complexType>"
+ "</xsd:element>"
+ "</xsd:sequence>"
+ "</xsd:complexType>"
+ "</xsd:element>"
+ "</xsd:schema>";
// Load the schema
factory.registerSchema(new StreamSource(new ByteArrayInputStream(schema.getBytes())));
// Turn on validation
factory.setValidating(true);
// Create a new static context from the factory
XStaticContext xStaticContext = factory.newStaticContext();
// Add a new namespace
xStaticContext.declareNamespace("my", "http://www.schematype.ibm.com/UDSimple");
// Create the XQueryExecutable
XQueryExecutable xQueryExecutable = factory.prepareXQuery(expression, xStaticContext);
// Create the input XML source
String xml = "<my:doc xmlns:my='http://www.schematype.ibm.com/UDSimple'>" +
"<name first='John'/><name first='David'/></my:doc>";
// Execute the expression and store the results in an XSequenceCursor
XSequenceCursor xSequenceCursor = xQueryExecutable.execute(new StreamSource(new ByteArrayInputStream(xml.getBytes())));