You can
assign fixed value for an element using the attribute “fixed”.
Syntax
<xs:element
name=”nameOfTheVariable” type=”typeOfTheVariable” fixed=”fixedValue” />
Example
<xs:element
name="dresscode" type="xs:string" fixed="Black and
White" />
Above
statement makes sure that dress code is “Black and White”. If you tries to
assign any value other than this, than XML validation check fails with
appropriate message.
student.xsd
<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="student"> <xs:complexType> <xs:sequence> <xs:element name="firstname" type="xs:string" /> <xs:element name="middlename" type="xs:string" /> <xs:element name="lastname" type="xs:string" /> <xs:element name="age" type="xs:integer" /> <xs:element name="department" type="xs:string" default="CSE" /> <xs:element name="dresscode" type="xs:string" fixed="Black and White" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
student.xml
<?xml version="1.0" encoding="UTF-8"?> <student xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="student.xsd"> <firstname>hari</firstname> <middlename>krishna</middlename> <lastname>gurram</lastname> <age>25</age> <department></department> <dresscode>abc</dresscode> </student>
Student.xml
assign value “abc” to dresscode, so validation check fail with below error.
XML
validation started.
Checking
file student.xml...
Referenced
entity at "student.xsd".
cvc-elt.5.2.2.2.2:
The value 'abc' of element 'dresscode' does not match the {value constraint}
value 'Black and White'. [10]
XML
validation finished.
No comments:
Post a Comment