Friday, 7 November 2014

XML : Default Value for Attribute

You can specify default value for an attribute in the schema.

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

Above statement assigns default value permanent for the attribute “type”.

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


If you don’t specify address type in your xml file, by default it takes as “permanent”.



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment