/*
1) register xmlschema
2) check TARGETNAMESPACE,SCHEMALOCATION
3) create table with xml datatype
4) select with explicit validate using target namespace and schema location
5) insert with explicit validate using target namespace and schema location
*/
-- 做一個xsd,並且指定target namespace
-- 存成 ex: c:\region2.xsd
< ?xml version="1.0"? >
< xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://localhost/region"
xmlns:r2="http://localhost/region" >
< xsd:element name="region2" >
< xsd:complexType >
< xsd:sequence >
< xsd:element name="regno" type="xsd:string" / >
< xsd:element name="regename" type="xsd:string" / >
< xsd:element name="regcname" type="xsd:string" / >
< /xsd:sequence >
< /xsd:complexType >
< /xsd:element >
< /xsd:schema >
-- register xmlschema
-- 給定schemalocation為http://localhost/region/region2.xsd
register xmlschema 'http://localhost/region/region2.xsd' from c:\region2.xsd as xsd_region2 complete;
-- 從system table: syscat.xsrobjects裡檢查是否已註冊成功
-- check一下 targetnamespace 與 schemalocation 這兩個欄位
select targetnamespace,schemalocation
from syscat.xsrobjects
where objectname = 'XSD_REGION2';
TARGETNAMESPACE SCHEMALOCATION
------------------------ ---------------------------------------------------
http://localhost/region http://localhost/region/region2.xsd
已選取 1 個記錄。
-- 手動建立一個table。
-- 這與oracle不同,oracle在xsd裡的xdb註明xml table後,oracle會自動產生
create table region2
(
id integer,
regioninfo xml
);
-- 新增前先select並寫好想要使用validate的方式,
-- 這裡使用uri (targetnamespace與schemalocation)來執行validate。
-- (pureXML(I) using DB2 9 指定的是 xmlschema ID來做validate)。
select xmlvalidate(xmlparse(document
'< ?xml version="1.0" encoding="UTF-8"? >
< r2:region2 xmlns:r2="http://localhost/region" >
< regno >1< /regno >
< regename >Northern< /regename >
< regcname >北區< /regcname >
< /r2:region2 >' preserve whitespace)
according to xmlschema uri 'http://localhost/region'
location 'http://localhost/region/region2.xsd')
from sysibm.sysdummy1;
-- 得到以下結果,並且未出現錯誤訊息
< r2:region2 xmlns:r2="http://localhost/region" >< regno >1< /regno >< regename >Northern< /regename >< regcname >北區< /regcname >< /r2:region2 >
-- 新增xml data至region2
insert into region2 values
(1,xmlvalidate(xmlparse(document
'< ?xml version="1.0" encoding="UTF-8"? >
< r2:region2 xmlns:r2="http://localhost/region" >
< regno >1< /regno >
< regename >Northern< /regename>
< regcname >北區< /regcname>
< /r2:region2 >' preserve whitespace
) according to xmlschema uri 'http://localhost/region'
location 'http://localhost/region/region2.xsd'));
-- 檢查是否資料新增至region2
select count(*) from region2
1
-----------
1
已選取 1 個記錄。