QXmlQuery¶

Synopsis¶
Functions¶
def
bindVariable
(localName, arg__2)def
bindVariable
(localName, query)def
bindVariable
(localName, value)def
bindVariable
(name, arg__2)def
bindVariable
(name, query)def
bindVariable
(name, value)def
evaluateTo
(callback)def
evaluateTo
(result)def
evaluateTo
(target)def
initialTemplateName
()def
isValid
()def
messageHandler
()def
namePool
()def
networkAccessManager
()def
queryLanguage
()def
setFocus
(document)def
setFocus
(documentURI)def
setFocus
(focus)def
setFocus
(item)def
setInitialTemplateName
(name)def
setInitialTemplateName
(name)def
setMessageHandler
(messageHandler)def
setNetworkAccessManager
(newManager)def
setQuery
(queryURI[, baseURI=QUrl()])def
setQuery
(sourceCode[, documentURI=QUrl()])def
setQuery
(sourceCode[, documentURI=QUrl()])def
setUriResolver
(resolver)def
uriResolver
()
Detailed Description¶
The
QXmlQuery
class compiles and executes queries written in the XQuery language.QXmlQuery
is typically used to query XML data, but it can also query non-XML data that has been modeled to look like XML.Using
QXmlQuery
to query XML data, as in the snippet below, is simple because it can use the built-inXML data model
as its delegate to the underlying query engine for traversing the data. The built-in data model is specified in XQuery 1.0 and XPath 2.0 Data Model.QXmlQuery query; query.setQuery("doc('index.html')/html/body/p[1]"); QXmlSerializer serializer(query, myOutputDevice); query.evaluateTo(&serializer);The example uses
QXmlQuery
to match the first paragraph of an XML document and thenoutput the result
to a device as XML.Using
QXmlQuery
to query non-XML data requires writing a subclass ofQAbstractXmlNodeModel
to use as a replacement for the built-in XML data model. The custom data model will be able to traverse the non-XML data as required by theQAbstractXmlNodeModel
interface. An instance of this custom data model then becomes the delegate used by the query engine to traverse the non-XML data. For an example of how to useQXmlQuery
to query non-XML data, see the documentation forQAbstractXmlNodeModel
.
Running XQueries¶
To run a query set up with
QXmlQuery
, call one of the evaluation functions.
evaluateTo
(QAbstractXmlReceiver *) is called with a pointer to an XML receiver, which receives the query results as a sequence of callbacks. The receiver callback class is like the callback class used for translating the output of a SAX parser.QXmlSerializer
, for example, is a receiver callback class for translating the sequence of callbacks for output as unformatted XML text.
evaluateTo
(QXmlResultItems
*) is called with a pointer to an iterator for an empty sequence of queryresult items
. The Java-like iterator allows the query results to be accessed sequentially.
evaluateTo
(QStringList
*) is likeevaluateTo
(QXmlResultItems
*), but the query must evaluate to a sequence of strings.
Running XPath Expressions¶
The XPath language is a subset of the XQuery language, so running an XPath expression is the same as running an XQuery query. Pass the XPath expression to
QXmlQuery
usingsetQuery()
.
Running XSLT Stylesheets¶
Running an XSLT stylesheet is like running an XQuery , except that when you construct your
QXmlQuery
, you must passXSLT20
to tellQXmlQuery
to interpret whatever it gets fromsetQuery()
as an XSLT stylesheet instead of as an XQuery . You must also set the input document by callingsetFocus()
.QXmlQuery query(QXmlQuery::XSLT20); query.setFocus(QUrl("myInput.xml")); query.setQuery(QUrl("myStylesheet.xsl")); query.evaluateTo(out);Note
Currently,
setFocus()
must be called beforesetQuery()
when using XSLT.Another way to run an XSLT stylesheet is to use the
xmlpatterns
command line utility.xmlpatterns myStylesheet.xsl myInput.xmlNote
For the current release, XSLT support should be considered experimental. See section XSLT conformance for details.
Stylesheet parameters are bound using
bindVariable()
.
Binding A Query To A Starting Node¶
When a query is run on XML data, as in the snippet above, the
doc()
function returns the node in the built-in data model where the query evaluation will begin. But when a query is run on a custom node model containing non-XML data, one of thebindVariable()
functions must be called to bind a variable name to a starting node in the custom model. A $variable reference is used in the XQuery text to access the starting node in the custom model. It is not necessary to declare the variable name external in the query. See the example in the documentation forQAbstractXmlNodeModel
.
Reentrancy and Thread-Safety¶
QXmlQuery
is reentrant but not thread-safe. It is safe to use the QxmlQuery copy constructor to create a copy of a query and run the same query multiple times. Behind the scenes,QXmlQuery
will reuse resources such as opened files and compiled queries to the extent possible. But it is not safe to use the same instance ofQXmlQuery
in multiple threads.
Error Handling¶
Errors can occur during query evaluation. Examples include type errors and file loading errors. When an error occurs:
The error message is sent to the
messageHandler()
.
hasError()
will returntrue
, orevaluateTo()
will returnfalse
;The results of the evaluation are undefined.
Resource Management¶
When a query runs, it parses documents, allocating internal data structures to hold them, and it may load other resources over the network. It reuses these allocated resources when possible, to avoid having to reload and reparse them.
When
setQuery()
is called, the query text is compiled into an internal data structure and optimized. The optimized form can then be reused for multiple evaluations of the query. Since the compile-and-optimize process can be expensive, repeating it for the same query should be avoided by using a separate instance ofQXmlQuery
for each query text.Once a document has been parsed, its internal representation is maintained in the
QXmlQuery
instance and shared among multipleQXmlQuery
instances.An instance of
QCoreApplication
must exist beforeQXmlQuery
can be used.
Event Handling¶
-
class
QXmlQuery
¶ QXmlQuery(queryLanguage[, np=QXmlNamePool()])
QXmlQuery(np)
QXmlQuery(other)
- param np
- param other
- param queryLanguage
QueryLanguage
Constructs an invalid, empty query that cannot be used until
setQuery()
is called.Note
This constructor must not be used if you intend to use this
QXmlQuery
to process XSL-T stylesheets. The other constructor must be used in that case.Constructs a query that will be used to run Xqueries or XSL-T stylesheets, depending on the value of
queryLanguage
. It will usenp
as its name pool.Note
If your
QXmlQuery
will process XSL-T stylesheets, this constructor must be used. The default constructor can only create instances ofQXmlQuery
for running XQueries.Note
The XSL-T support in this release is considered experimental. See the XSLT conformance for details.
See also
Constructs a query that will use
np
as its name pool. The query cannot be evaluated untilsetQuery()
has been called.Constructs a
QXmlQuery
that is a copy ofother
. The new instance will share resources with the existing query to the extent possible.
-
PySide2.QtXmlPatterns.QXmlQuery.
QueryLanguage
¶ Specifies whether you want
QXmlQuery
to interpret the input tosetQuery()
as an XQuery or as an XSLT stylesheet.Constant
Description
QXmlQuery.XQuery10
XQuery 1.0.
QXmlQuery.XSLT20
XSLT 2.0 The selector, the restricted XPath pattern found in W3C XML Schema 1.1 for uniqueness contraints. Apart from restricting the syntax, the type check stage for the expression assumes a sequence of nodes to be the focus. The field, the restricted XPath pattern found in W3C XML Schema 1.1 for uniqueness contraints. Apart from restricting the syntax, the type check stage for the expression assumes a sequence of nodes to be the focus. Signifies XPath 2.0. Has no effect in the public API, it’s used internally. As With and , the type check stage for the expression assumes a sequence of nodes to be the focus.
See also
-
PySide2.QtXmlPatterns.QXmlQuery.
bindVariable
(localName, arg__2)¶ - Parameters
localName – unicode
arg__2 –
QIODevice
This is an overloaded function.
If
localName
is a validNCName
, this function is equivalent to the following snippet.QXmlNamePool namePool(query.namePool()); query.bindVariable(QXmlName(namePool, localName), device);
A
QXmlName
is constructed fromlocalName
, and is passed to the appropriate overload along withdevice
.See also
-
PySide2.QtXmlPatterns.QXmlQuery.
bindVariable
(localName, value) - Parameters
localName – unicode
value –
QXmlItem
This is an overloaded function.
This function constructs a
QXmlName
fromlocalName
using the query’snamespace
. The function then behaves as the overloaded function. It is equivalent to the following snippet.QXmlNamePool namePool(query.namePool()); query.bindVariable(QXmlName(namePool, localName), value);
-
PySide2.QtXmlPatterns.QXmlQuery.
bindVariable
(localName, query) - Parameters
localName – unicode
query –
QXmlQuery
This is an overloaded function.
Has the same behavior and effects as the function being overloaded, but takes the variable name
localName
as aQString
.query
is used as in the overloaded function.
-
PySide2.QtXmlPatterns.QXmlQuery.
bindVariable
(name, arg__2) - Parameters
name –
QXmlName
arg__2 –
QIODevice
Binds the variable
name
to thedevice
so that $``name`` can be used from within the query to refer to thedevice
. TheQIODevice
device
is exposed to the query as a URI of typexs:anyURI
, which can be passed to thefn:doc()
function to be read. E.g., this function can be used to pass an XML document in memory tofn:doc
.QByteArray myDocument; QBuffer buffer(&myDocument); // This is a QIODevice. buffer.open(QIODevice::ReadOnly); QXmlQuery query; query.bindVariable("myDocument", &buffer); query.setQuery("doc($myDocument)");
The caller must ensure that
device
has been opened with at leastReadOnly
prior to this binding. Otherwise, behavior is undefined.If the query will access an XML document contained in a
QString
, use aQBuffer
as shown in the following snippet. Suppose myQString contains<document>content</document>
QBuffer device; device.setData(myQString.toUtf8()); device.open(QIODevice::ReadOnly); QXmlQuery query; query.setQuery("doc($inputDocument)/query[theDocument]"); query.bindVariable("inputDocument", &device);
name
must not be null .name
.isNull() must return false. Ifname
has already been bound, its previous binding will be overridden. The URI thatname
evaluates to is arbitrary and may change.If the type of the variable binding changes (e.g., if a previous binding by the same name was a
QVariant
, or if there was no previous binding),isValid()
will returnfalse
, and recompilation of the query text is required. To recompile the query, callsetQuery()
. For this reason,bindVariable()
should be called beforesetQuery()
, if possible.Note
device
must not be deleted while thisQXmlQuery
exists.
-
PySide2.QtXmlPatterns.QXmlQuery.
bindVariable
(name, value) -
Binds the variable
name
to thevalue
so that $``name`` can be used from within the query to refer to thevalue
.name
must not be null .name
.isNull() must return false. Ifname
has already been bound by a previous call, its previous binding will be overridden.If
value
is null so thatvalue
.isNull() returns true, andname
already has a binding, the effect is to remove the existing binding forname
.To bind a value of type
QString
orQUrl
, wrap the value in aQVariant
such thatQXmlItem
‘sQVariant
constructor is called.All strings processed by the query must be valid XQuery strings, which means they must contain only XML 1.0 characters. However, this requirement is not checked. If the query processes an invalid string, the behavior is undefined.
See also
-
PySide2.QtXmlPatterns.QXmlQuery.
bindVariable
(name, query) -
Binds the result of the query
query
, to a variable by namename
.Evaluation of
query
will be commenced when this function is called.If
query
is invalid, behavior is undefined.query
will be copied.See also
-
PySide2.QtXmlPatterns.QXmlQuery.
evaluateTo
(callback)¶ - Parameters
callback –
QAbstractXmlReceiver
- Return type
bool
Evaluates this query and sends the result as a sequence of callbacks to the receiver
callback
.QXmlQuery
does not take ownership ofcallback
.If an error occurs during the evaluation, error messages are sent to
messageHandler()
andfalse
is returned.If this query
is invalid
,false
is returned and the behavior is undefined. Ifcallback
is null, behavior is undefined.See also
-
PySide2.QtXmlPatterns.QXmlQuery.
evaluateTo
(target) - Parameters
target –
QIODevice
- Return type
bool
Evaluates the query or stylesheet, and writes the output to
target
.QXmlSerializer
is used to write the output totarget
. In a future release, it is expected that this function will be changed to respect serialization options set in the stylesheet.If an error occurs during the evaluation, error messages are sent to
messageHandler()
andfalse
is returned.If
target
isnull
, or is not opened in at leastWriteOnly
mode, the behavior is undefined.QXmlQuery
does not take ownership oftarget
.This is an overloaded function.
-
PySide2.QtXmlPatterns.QXmlQuery.
evaluateTo
(result) - Parameters
result –
QXmlResultItems
Starts the evaluation and makes it available in
result
. Ifresult
is null, the behavior is undefined. The evaluation takes place incrementally (lazy evaluation), as the caller usesnext()
to get the next result.See also
-
PySide2.QtXmlPatterns.QXmlQuery.
initialTemplateName
()¶ - Return type
Returns the name of the XSL-T stylesheet template that the processor will call first when running an XSL-T stylesheet. This function only applies when using
QXmlQuery
to process XSL-T stylesheets. By default, no initial template is set. In that case, a default constructedQXmlName
is returned.See also
-
PySide2.QtXmlPatterns.QXmlQuery.
isValid
()¶ - Return type
bool
Returns true if this query is valid. Examples of invalid queries are ones that contain syntax errors or that have not had
setQuery()
called for them yet.
-
PySide2.QtXmlPatterns.QXmlQuery.
messageHandler
()¶ - Return type
Returns the message handler that handles compile and runtime messages for this
QXmlQuery
.See also
-
PySide2.QtXmlPatterns.QXmlQuery.
namePool
()¶ - Return type
Returns the name pool used by this
QXmlQuery
for constructingnames
. There is no setter for the name pool, because mixing name pools causes errors due to name confusion.
-
PySide2.QtXmlPatterns.QXmlQuery.
networkAccessManager
()¶ - Return type
QNetworkAccessManager
Returns the network manager, or 0 if it has not been set.
See also
-
PySide2.QtXmlPatterns.QXmlQuery.
queryLanguage
()¶ - Return type
Returns a value indicating what this
QXmlQuery
is being used for. The default isXQuery10
, which means theQXmlQuery
is being used for running XQuery and XPath queries.XSLT20
can also be returned, which indicates theQXmlQuery
is for running XSL-T spreadsheets.
-
PySide2.QtXmlPatterns.QXmlQuery.
setFocus
(document)¶ - Parameters
document –
QIODevice
- Return type
bool
Sets the focus to be the
document
read from theQIODevice
and returns true. Ifdocument
cannot be loaded, false is returned.QXmlQuery
does not take ownership ofdocument
. The user guarantees that a document is available from thedocument
device and that the document is not empty. The device must be opened in at least read-only mode.document
must stay in scope as long as the current query is active.This is an overloaded function.
-
PySide2.QtXmlPatterns.QXmlQuery.
setFocus
(focus) - Parameters
focus – unicode
- Return type
bool
This function behaves identically to calling the
setFocus()
overload with aQIODevice
whose content isfocus
encoded as UTF-8. That is,focus
is treated as if it contained an XML document.Returns the same result as the overload.
This is an overloaded function.
-
PySide2.QtXmlPatterns.QXmlQuery.
setFocus
(documentURI) - Parameters
documentURI –
QUrl
- Return type
bool
This is an overloaded function.
Sets the focus to be the document located at
documentURI
and returns true. IfdocumentURI
cannot be loaded, false is returned. It is undefined at what time the document may be loaded. When loading the document, the message handler and URI resolver set on thisQXmlQuery
are used.If
documentURI
is empty or is not a valid URI, the behavior of this function is undefined.
-
PySide2.QtXmlPatterns.QXmlQuery.
setFocus
(item) - Parameters
item –
QXmlItem
Sets the focus to
item
. The focus is the set of items that the context item expression and path expressions navigate from. For example, in the expression p/span , the element that p evaluates to is the focus for the following expression, span .The focus can be accessed using the context item expression, i.e., dot (“.”).
By default, the focus is not set and is undefined. It will therefore result in a dynamic error,
XPDY0002
, if the focus is attempted to be accessed. The focus must be set before the query is set withsetQuery()
.There is no behavior defined for setting an item which is null.
-
PySide2.QtXmlPatterns.QXmlQuery.
setInitialTemplateName
(name)¶ - Parameters
name – unicode
This is an overloaded function.
Sets the name of the initial template to
localName
, which must be a validlocal name
. The initial template is the one the processor calls first, instead of attempting to match a template to the context node (if any). If an initial template is not set, the standard order of template invocation will be used.This function only applies when using
QXmlQuery
to process XSL-T stylesheets. The name becomes part of the compiled stylesheet. Therefore, this function must be called before callingsetQuery()
.If
localName
is not a validlocal name
, the effect is undefined. If the stylesheet has no template namedlocalName
, the processor will use the standard order of template invocation.See also
-
PySide2.QtXmlPatterns.QXmlQuery.
setInitialTemplateName
(name) - Parameters
name –
QXmlName
Sets the
name
of the initial template. The initial template is the one the processor calls first, instead of attempting to match a template to the context node (if any). If an initial template is not set, the standard order of template invocation will be used.This function only applies when using
QXmlQuery
to process XSL-T stylesheets. The name becomes part of the compiled stylesheet. Therefore, this function must be called before callingsetQuery()
.If the stylesheet has no template named
name
, the processor will use the standard order of template invocation.See also
-
PySide2.QtXmlPatterns.QXmlQuery.
setMessageHandler
(messageHandler)¶ - Parameters
messageHandler –
QAbstractMessageHandler
Changes the
message handler
for thisQXmlQuery
toaMessageHandler
. The query sends all compile and runtime messages to this message handler.QXmlQuery
does not take ownership ofaMessageHandler
.Normally, the default message handler is sufficient. It writes compile and runtime messages to stderr . The default message handler includes color codes if stderr can render colors.
Note that changing the message handler after the query has been compiled has no effect, i.e. the query uses the same message handler at runtime that it uses at compile time.
When
QXmlQuery
callsmessage()
, the arguments are as follows:message() argument
Semantics
QtMsgType
typeOnly
QtWarningMsg
andQtFatalMsg
are used. The former identifies a compile or runtime warning, while the latter identifies a dynamic or static error.const
QString
& descriptionAn XHTML document which is the actual message. It is translated into the current language.
const
QUrl
&identifierIdentifies the error with a URI, where the fragment is the error code, and the rest of the URI is the error namespace.
const
QSourceLocation
& sourceLocationIdentifies where the error occurred.
See also
-
PySide2.QtXmlPatterns.QXmlQuery.
setNetworkAccessManager
(newManager)¶ - Parameters
newManager –
QNetworkAccessManager
Sets the network manager to
newManager
.QXmlQuery
does not take ownership ofnewManager
.See also
-
PySide2.QtXmlPatterns.QXmlQuery.
setQuery
(sourceCode[, documentURI=QUrl()])¶ - Parameters
sourceCode –
QIODevice
documentURI –
QUrl
Sets this
QXmlQuery
to an XQuery read from thesourceCode
device. The device must have been opened with at leastReadOnly
.documentURI
represents the query obtained from thesourceCode
device. It is the base URI of the static context, as defined in the XQuery language. It is used internally to resolve relative URIs that appear in the query, and for message reporting.documentURI
can be empty. If it is empty, theapplication file path
is used. If it is not empty, it may be either relative or absolute. If it is relative, it is resolved itself against theapplication file path
before it is used. IfdocumentURI
is neither a valid URI nor empty, the result is undefined.If the query contains a static error (e.g. syntax error), an error message is sent to the
messageHandler()
, andisValid()
will return false .Variables must be bound before is called.
The encoding of the XQuery in
sourceCode
is detected internally using the rules for setting and detecting encoding of XQuery files, which are explained in the XQuery language.If
sourceCode
isnull
or not readable, or ifdocumentURI
is not a valid URI, behavior is undefined.See also
-
PySide2.QtXmlPatterns.QXmlQuery.
setQuery
(sourceCode[, documentURI=QUrl()]) - Parameters
sourceCode – unicode
documentURI –
QUrl
This is an overloaded function.
The behavior and requirements of this function are the same as for
setQuery
(QIODevice
*, constQUrl
&), after the XQuery has been read from the IO device into a string. BecausesourceCode
is already a Unicode string, detection of its encoding is unnecessary.
-
PySide2.QtXmlPatterns.QXmlQuery.
setQuery
(queryURI[, baseURI=QUrl()]) - Parameters
queryURI –
QUrl
baseURI –
QUrl
Sets this
QXmlQuery
to the XQuery read from thequeryURI
. UseisValid()
after calling this function. If an error occurred readingqueryURI
, e.g., the query does not exist, cannot be read, or is invalid,isValid()
will return false .The supported URI schemes are the same as those in the XQuery function
fn:doc
, except that queryURI can be the object of a variable binding.baseURI
is the Base URI of the static context, as defined in the XQuery language. It is used internally to resolve relative URIs that appear in the query, and for message reporting. IfbaseURI
is empty,queryURI
is used. Otherwise,baseURI
is used, and it is resolved against theapplication file path
if it is relative.If
queryURI
is empty or invalid, or ifbaseURI
is invalid, the behavior of this function is undefined.
-
PySide2.QtXmlPatterns.QXmlQuery.
setUriResolver
(resolver)¶ - Parameters
resolver –
QAbstractUriResolver
Sets the URI resolver to
resolver
.QXmlQuery
does not take ownership ofresolver
.See also
-
PySide2.QtXmlPatterns.QXmlQuery.
uriResolver
()¶ - Return type
Returns the query’s URI resolver. If no URI resolver has been set, Qt XML Patterns will use the URIs in queries as they are.
The URI resolver provides a level of abstraction, or polymorphic URIs . A resolver can rewrite logical URIs to physical ones, or it can translate obsolete or invalid URIs to valid ones.
Qt XML Patterns calls the URI resolver for all URIs it encounters, except for namespaces. Specifically, all builtin functions that deal with URIs (
fn:doc()
, andfn:doc-available()
).In the case of
fn:doc()
, the absolute URI is the base URI in the static context (which most likely is the location of the query). Rather than use the URI the user specified, the return value ofresolve()
will be used.When Qt XML Patterns calls
resolve()
the absolute URI is the URI mandated by the XQuery language, and the relative URI is the URI specified by the user.See also