Thursday, March 19, 2009

How to put restriction in XSD file to validate XML

In XSD file you can put data restriction then XML should satisfy those restriction, otherwise XML would not get validated.
Suppose some number I want only from 100 to 500. Or some name I want only India, US, UK. In this situation We can put the restriction in XSD file.
I am giving one example below, as per the this XSD number can only accept from 100 (Inclusice) to upto 500 (exclusive) and name would accept only Binod, Pramod, Manish.
Using this below XSD you can check xml with give some thing other than restricted value.

hrrecord.xsd

<?xml version="1.0" encoding="UTF-8"?><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://mycompany.com/hr/schemas" xmlns:schemas="http://mycompany.com/hr/schemas;
<xs:element name="HolidayRequest">
<xs:complexType>
<xs:sequence> <xs:element maxOccurs="unbounded" ref="schemas:Student"/>
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:element name="Student">
<xs:complexType>
<xs:sequence>
<xs:element ref="schemas:Holiday"/>
<xs:element ref="schemas:Employee"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Holiday">
<xs:complexType>
<xs:sequence>
<xs:element ref="schemas:StartDate"/>
<xs:element ref="schemas:EndDate"/>
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:element name="StartDate" type="xs:NMTOKEN"/>
<xs:element name="EndDate" type="xs:NMTOKEN"/>
<xs:element name="Employee"> <xs:complexType>
<xs:sequence>
<xs:element ref="schemas:Number"/>
<xs:element ref="schemas:FirstName"/>
<xs:element ref="schemas:LastName"/> </xs:sequence> </xs:complexType> </xs:element>
<xs:element name="Number">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="100"></xs:minInclusive>
<xs:maxExclusive value="500"></xs:maxExclusive>
</xs:restriction>
</xs:simpleType>
</xs:element>

<xs:element name="FirstName">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Binod"></xs:enumeration>
<xs:enumeration value="Pramod"></xs:enumeration>
<xs:enumeration value="Manish"></xs:enumeration>
</xs:restriction>
</xs:simpleType>
</xs:element>

<xs:element name="LastName" type="xs:NCName"/>
</xs:schema>

If you will give name other than specfied in XSD you will get this error
com.sun.msv.verifier.ValidityViolation: the value is not a member of the enumeration: ("Binod"/"Manish"/"Pramod")
at com.sun.msv.verifier.Verifier.onError(Verifier.java:367)

If you will give number more than or equal to 500 then you will get error
com.sun.msv.verifier.ValidityViolation: the value is out of the range (maxExclusive specifies 500).
at com.sun.msv.verifier.Verifier.onError(Verifier.java:367)

No comments:

Post a Comment

You can put your comments here (Either feedback or your Question related to blog)