Reputation: 13063
I'm creating an XSD where one of the elements needs to be either empty, or a value from an enumeration:
<xs:element name="MyElement" nillable="true">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="A" />
<xs:enumeration value="B" />
<xs:enumeration value="C" />
</xs:restriction>
</xs:simpleType>
</xs:element>
I had hoped that by setting the nillable
attribute to true
, it would allow A, B, C or an empty value:
<MyElement></MyElement>
But apparently that is not valid:
The Enumeration constraint failed.
I've also tried to explicitly add the empty value to the enumeration:
<xs:enumeration value="" />
But no luck either:
The Enumeration constraint failed.
Currently, I'm using a pattern instead:
<xs:pattern value="[ABC]{0,1}" />
This works, but I find this is an awful way to go for such a simple requirement. Surely there must be something I can do to allow "anything from the enumeration or empty"? Oh and don't suggest setting minOccurs
to 0
, the tag has to be there at all times.
Upvotes: 3
Views: 9492
Reputation: 6016
I don't know what validator are you using but if you add <xs:enumeration value="" />
as a child of the restriction tag then <MyElement></MyElement>
is valid (I'm sure of that and I have already tested it in oXygen and a couple of online validators just in case).
So the correct way to do what you want to do it's to use an empty enumeration value or use a pattern restriction. In other words, the two solutions you provide in your questions are correct although your validator doesn't think so with the enumeration (maybe it's a bug, maybe a typo in the full Schema, I don't know).
Nillable
means that in the XML instance the element can have the nil attribute set to true and then it should be empty. Example:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="MyElement" type="xs:string" nillable="true"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
In the following example MyElement have the nil attribute set to true and it's empty, so it's valid against the example XML Schema (notice that if MyElement have content and nil set to true, then is not valid)
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:ns="http://www.w3.org/2001/XMLSchema-instance">
<MyElement ns:nil="true"></MyElement>
</root>
So in my opinion, using nillable it's not a good solution as you have to add an attribute to your XML instance. Instead of using nillable I would suggest to use enumeration as you were trying to do, and check that strange behavior of the validator.
Upvotes: 3