Attributes
are optional by default. You can specify required attributes using “use”
attribute of element tag.
Example
<xs:element name=”type” type=”xs:string” use=”required” /> <xs:element name="address"> <xs:complexType> <xs:sequence> <xs:element name="city" type="xs:string" /> <xs:element name="district" type="xs:string" /> <xs:element name="state" type="xs:string" /> <xs:element name="country" type="xs:string" /> </xs:sequence> <xs:attribute name="type" type="xs:string" use="required" /> <xs:attribute name="from" type="xs:date" /> </xs:complexType> </xs:element>
Above
code snippet specifies “type” for the element “address” is a required
attribute.
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:element name="address"> <xs:complexType> <xs:sequence> <xs:element name="city" type="xs:string" /> <xs:element name="district" type="xs:string" /> <xs:element name="state" type="xs:string" /> <xs:element name="country" type="xs:string" /> </xs:sequence> <xs:attribute name="type" type="xs:string" use="required" /> <xs:attribute name="from" type="xs:date" /> </xs:complexType> </xs:element> </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>Black and White</dresscode> <address from="1989-05-06"> <city>Ongole</city> <district>Prakasam</district> <state>Andhra Pradesh</state> <country>India</country> </address> </student>
Above
xml file doesn’t specifies the type attribute for address element. So when you
tries to validate you will get below error.
XML
validation started.
Checking
file:student.xml...
Referenced
entity at "file:student.xsd".
cvc-complex-type.4:
Attribute 'type' must appear on element 'address'. [11]
XML
validation finished.
No comments:
Post a Comment