Skip to Main Content

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question.

Asked: January 11, 2016 - 2:27 pm UTC

Last updated: January 12, 2016 - 1:46 pm UTC

Version: 11g express edition

Viewed 1000+ times

You Asked

In the below link they explained the how to validate xml against the xsd, But they are validating only one record, if we have more records, we have to create a xml file and do the validation. How to do the validate a xml file with corresponding xsd by using xmltype() function.


I am new to this area. Please explain or give an example for this.


http://when-others-then-null.blogspot.no/2013/01/validate-xml-in-oracle-against-xsd.html?showComment=1452517262064#c6723554880719946371

and Chris said...

You can use the XMLIsValid function to verify XMLType rows in a table.

This returns 1 if the XML conforms and 0 if it doesn't.

Using the linked example:

BEGIN   

   dbms_xmlschema.registerSchema(schemaURL   => 'xsd1.xsd', 
                                 schemaDoc   => '<?xml version="1.0" encoding="UTF-8"?> 
 <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">   
 <xs:element name="userdetails">     
 <xs:complexType>       
 <xs:sequence>             
 <xs:element name="username" type="xs:string"/>         
 <xs:element name="password"  type="xs:string"/> 
 </xs:sequence>     
 </xs:complexType>   
 </xs:element> 
 </xs:schema>'); 
END; 
/ 

create table t (
  x xmltype
);

-- valid XML
insert into t values (XMLTYPE('
<userdetails xsi:noNamespaceSchemaLocation="xsd1.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <username>Fred</username>
  <password>pass123</password>
</userdetails>'));

-- does not conform to XSD
insert into t values (XMLTYPE('
<userdetails xsi:noNamespaceSchemaLocation="xsd1.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <user>Fred</user>
  <password>pass123</password>
</userdetails>'));
           
-- find rows that do not conform
select t.*
from   t
where  XMLIsValid(x, 'xsd1.xsd') = 0;

X                                                                                                                                                              
-------------------------------------------------------
<userdetails xsi:noNamespaceSchemaLocation="xsd1.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <user>Fred</user>
  <password>pass123</password>
</userdetails>


Is this answer out of date? If it is, please let us know via a Comment

More to Explore

DBMS_XMLSCHEMA

More on PL/SQL routine DBMS_XMLSCHEMA here