How to model variant data structures in XML Schema
How would you model a variant data structure in XML Schema, without using xsi:type
?
My goal is to define a schema for an element named <property>
whose attributes and attribute types depend on the datatype
attribute; for example:
<property datatype="integer" default="1234"/>
<property datatype="string" default="Abcde" maxlength="255"/>
Here, the default
attribute of the integer-typed property shall only accept valid integer values, whereas the default
attribute of the string-typed property sh开发者_StackOverflowall accept any characters.
Furthermore, the maxlength
attribute shall be allowed only if datatype="string"
.
I.e. a schema validation error should occur on both of the following properties:
<property datatype="integer" default="NotAnInteger"/>
<property datatype="integer" default="12345" maxlength="100"/> <!-- maxlength not allowed -->
I know that if I would use xsi:type
instead of datatype
, this would be easy to model in XML Schema.
There are, however, at least two reasons, why I do not want to use xsi:type
here:
I have read in many places that it is not considered good style to use
xsi:type
, e.g. xsi:type is Evil or Smart but useless, part 3.The name
xsi:type
simply does not express the purpose of the attribute precisely enough. I rather would preferdatatype
.
You can do this using Conditional Type Assignment in XSD 1.1, which is implemented in current releases of Xerces and Saxon. It can't be done in XSD 1.0 - it's a well known restriction (often referred to under the label "co-occurrence constraints").
精彩评论