There are a number of advantages of using schemas with queries:
If an input document has been validated against a schema, its structure and data content are predictable. If the schema says that there will always be a number
child of product
, and your input document was validated, you can be sure that a number
child will exist for each product
. You do not need to check for its existence before you use it in an expression.
The schema provides type information to the query processor about the values in the instance document. For example, it can tell us that the number
element contains an integer value. This is useful, for example, if you write a query that returns results sorted by number
. The query processor will know that the number
values should be sorted as integers and not strings, and will therefore sort 100 after 99. If they were sorted as strings, 100 would come before 99.
Schemas can be used in static analysis to determine the expected type of an expression. Using schemas, you might discover errors in the query that were not otherwise apparent. Schemas can also help you debug your queries more quickly and easily by providing more useful error messages. To use a SQL analogy, you wouldn't want a SQL statement that had a misspelled column name to come back with nothing instead of raising an error. Without XML schemas, this is exactly what your XQuery queries will do if you misspell an element name or specify an invalid path: return nothing.
The more a processor knows about the structure of the input documents, the more it can optimize access to them. For example, if a schema is present, an expression such as catalog//number
is a simple matter of looking at the grandchildren of catalog
and returning those named number
. If no schema is present, every node of the document must be traversed to find number
elements.
Type-related expressions, such as instance of
and typeswitch
, can be used on user-defined types in the schema. For example, you could write an expression that processes the product
element differently depending on whether it is of type ShirtType
, HatType
, etc.
A query might be designed to produce results that conform to a particular XML language, such as XHTML. Performing schema validation in the query ensures that the results are valid XHTML. If the query isn't generating valid XHTML, the query processor may be able to pinpoint the error in your query.
Some query users are not concerned about these benefits, and they feel that using schemas adds too much complexity. For these users, it is entirely possible to use XQuery without schemas. If no schema is present, all of the elements and attributes are untyped. This means that they are assigned generic types (xs:untyped
and xs:untypedAtomic
) that allow any content or value.
3.144.9.124