Friday, 7 November 2014

xml : Fixed Value for Attribute


You can specify fixed value for the attribute using XML Schema.

Example
<xs:attribute name="type" type="xs:string" fixed="permanent" />

Above statement makes sure that the attribute “type” must contains value “permanent” only.

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" fixed="permanent" />
                    </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 type="temporary">
        <city>Ongole</city>
        <district>Prakasam</district>
        <state>Andhra Pradesh</state>
        <country>India</country>
    </address>
</student>


student.xml assign type value for address element as “temporary” which is not valid as per schema. When you tries to validate student.xml against student.xsd, you will get below error.

XML validation started.
Checking file:student.xml...
Referenced entity at "file:student.xsd".
cvc-complex-type.3.1: Value 'temporary' of attribute 'type' of element 'address' is not valid with respect to the corresponding attribute use. Attribute 'type' has a fixed value of 'permanent'. [11]
XML validation finished.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment