Reputation: 899
I want to create an XSD for an XML. I have XML elements declared with the xs:string
data type where that data is mandatory. I created an XSD and set minOccurs="1"
, but then found out that its purpose is to just check whether the element appears in the XML. I also discovered that there is a keyword use="required"
but it is for attributes and cannot be used in the XML element. I finally tried nillable="false"
but the XSD was validated without any data in my element.
This is my document:
<HelloWorld>
<Name></Name>
<Gender></Gender>
</HelloWorld>
And XSD:
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="HelloWorld">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:string" name="Name" minOccurs="1"/>
<xs:element type="xs:int" name="Gender"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Here I want the data in the Name
element to always be present (it's a mandatory field). When I validate this file it will throw an error for Gender
saying that it contains an invalid integer. If you put some numbers it will start validating successfully but it won't check the data inside the Name
element.
Upvotes: 1
Views: 1691
Reputation: 23627
It validates because an empty string is a valid xs:string
. Gender
fails when empty because an empty string is not a valid xs:int
.
If you want to force Name
validation to fail when empty, you have to add a restriction. You choose what kind of restriction you need: a minimum string length, certain string characters (an enumeration or a pattern), etc. In the example below, I added a restriction which requires that the string be at least one character long:
<xs:element name="Name" minOccurs="1">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
Now it will fail if Name
is empty.
Upvotes: 1