In DB2, validation of XML documents
against XML Schemas is optional. If you choose to validate XML
documents in DB2, the most typical scenario is to validate XML documents
when they are inserted or loaded into the database. This makes sense:
if you ensure that the XML that enters the database is valid, then
subsequent queries can assume that the data is valid and complies with a
particular XML Schema.

Here is a simple example for document validation in INSERT and UPDATE
statements, based on an XML Schema that was registered in the DB2 XML Schema Repository (XSR) under the SQL name db2admin.myschema:

CREATE TABLE mytable (id INTEGER NOT NULL PRIMARY KEY, doc XML);

INSERT INTO mytableVALUES(?, XMLVALIDATE(? ACCORDING TO XMLSCHEMA ID db2admin.myschema));

There are also cases when you might want to validate XML as part of a query. There can be several reasons for that:

Documents were inserted or updated without validation and you need to validate them before consumptions.

You wish to validate XML documents against a different schema than the one was used for validation upon insert or update.

You are extracting fragments of stored XML documents and wish to validate them against a specific schema.

Your queries are constructing entirely new XML documents and you
wish to vaidate that the constructed XML complies with a given schema.

Regardless of the motivation, XML validation in a query is simple.

You can simply use the XMLVALIDATE
function in a SELECT statement. All the same options for XMLVALIDATE
are allowed as if you would use it in an INSERT or UPDATE statement.
Let’s look at several examples:

This query above reads a specific document and performs schema
validation against the XML Schema that was registered as
db2admin.myschema.
If the selected document is valid for the specified schema, the document is returned.
If the selected document is not valid for the specified schema, the
query fails and produces an error code that points to why the schema is
violated.

Instead of the XML column name doc, the XMLVALIDATE
function can take any argument of type XML, such the result of an
XMLQUERY function. The following query uses the XMLQUERY function to
extract just the message body from an XML document and validates it
against the XML Schema db2admin.msgbodyXSD: