XSD validation is not happening while setting nillable="false"

Viewed 575

Here is the xml file which I want to validate against below XML schema.

<?xml version="1.0" encoding="UTF-8"?>
<Students>
<Name></Name>
<Phone>0123987654</Phone>
<Address>
In front of PNB
</Address>
<Dob>2002-09-24</Dob>
</Students>

XML Schema

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Students">
<xs:complexType>
<xs:sequence>
<xs:element name="Name" type="xs:string" nillable="false"  />
<xs:element name="Phone" type="xs:integer"/>
<xs:element name="Address" type="xs:string"/>
<xs:element name="Dob" type="xs:date" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

During validation, I didn't notice any error though Name Field was empty and nillable="false" was set in schema. The name field shouldn't be empty and if no value is provided in error then validation error should have been thrown. Can anybody suggest solution how same can be implemented through MinLength as for simpletype it is possible for me but complex type not sure how to proceed further.

1 Answers

The XSD nillable attribute is a way to allow empty content, not a way to disallow it.

Here's an excerpt from the W3C spec for XSD 1.1:

If {nillable} is true, then an element with no text or element content can be ·valid· despite a {type definition} which would otherwise require content, if it carries the attribute xsi:nil with the value true

So nillable="true" defines an exception to some other rule which would forbid an empty element. The exception is triggered specifically by specifying xsi:nil="true" on the instance.

Setting nillable="false" just asserts that you can't add an xsi:nil attribute to the element, it doesn't make a difference to whether the element can be otherwise empty. Unless modified by some other part of the schema, this is the default for all elements, as shown further down the spec:

{nillable} The ·actual value· of the nillable [attribute], if present, otherwise false.

To specify that an element can't be empty, you need some other rule, such as declaring a simple type which specifies a base type of string and a minimum length of 1:

<xs:simpleType name="nonEmptyString">
    <xs:restriction base="xs:string">
        <xs:minLength value="1" />
    </xs:restriction>
</xs:simpleType>
Related