Lesson 7: Validating XML documents against XML schemas
This lesson shows you how to validate XML documents. You can validate your XML documents against XML schemas only; validation against DTDs is not supported. However, although you cannot validate against DTDs, you can insert documents that contain a DOCTYPE or that refer to DTDs.
You can use tools such as those in IBM® Rational® Application Developer to help generate XML schemas from various sources, including DTDs, tables, and XML documents.
Before you can validate, you must register your XML schema with the built-in XML schema repository (XSR). This process involves registering each XML schema document that makes up the XML schema and then completing the registration. One method of registering an XML schema is through commands.
REGISTER XMLSCHEMA 'http://posample.org' FROM 'file:///c:/sqllib/samples/xml/customer.xsd' AS posample.customer COMPLETE~
SELECT OBJECTSCHEMA, OBJECTNAME FROM SYSCAT.XSROBJECTS~ OBJECTSCHEMA OBJECTNAME -------------------- -------------------- POSAMPLE CUSTOMER
You can now use the XML schema for validation. You typically perform validation during an INSERT or UPDATE operation, using the XMLVALIDATE function. The INSERT or UPDATE operation for which you specify XMLVALIDATE occurs only if the validation succeeds.
INSERT INTO Customer(Cid, Info) VALUES (1003, XMLVALIDATE (XMLPARSE (DOCUMENT '<customerinfo xmlns="http://posample.org" Cid="1003"> <name>Robert Shoemaker</name> <addr country="Canada"> <street>1596 Baseline</street> <city>Aurora</city> <prov-state>Ontario</prov-state> <pcode-zip>N8X 7F8</pcode-zip> </addr> <phone type="work">905-555-7258</phone> <phone type="home">416-555-2937</phone> <phone type="cell">905-555-8743</phone> <phone type="cottage">613-555-3278</phone> </customerinfo>' PRESERVE WHITESPACE ) ACCORDING TO XMLSCHEMA ID posample.customer ))~
The XML document in this example is passed as character data. However, XMLVALIDATE operates only on XML data. Because the XML document is passed as character data, you must explicitly parse the data using the XMLPARSE function. The XMLPARSE function parses its argument as an XML document and returns an XML value.
The Db2® database server performs implicit parsing for some operations, For example, implcit parsing occurs when you assign a host variable, parameter marker, or SQL expression with a string data type (character, graphic or binary) to an XML column in an INSERT, UPDATE, DELETE, or MERGE statement. For information about XML parsing, see the related link.
This query should return three XML documents, one of which is the document that you just inserted.
SELECT Info FROM Customer~