问题
Is it possible to extend an element in XSD 1.1 based on another element's value?
For example:
<Field>
<Title>Text Field</Title>
<Type>Text</Type>
<Length>100</Length>
</Field>
<Field>
<Title>Date Field</Title>
<Type>Date</Type>
<Format>mm/dd/yyyy</Format>
<Field>
Both Field elements share common Title and Type elements.
For the Text Field, it can have a Length
element, but Date cannot.
The Date Field
can have Format
, but Text
cannot.
I'd like to extend both Text and Date fields, if possible, from a common type.
Note: I'm assuming the above is not possible in XSD 1.0
回答1:
No, an element's type cannot depend upon the value of another element in XSD 1.0 or XSD 1.1.
Alternative Solutions
Redesign your XML. Rather than have a generic
Field
element with a genericType
child element, include the type in the name of each element:<Text> <Title>Text Field</Title> <Length>100</Length> </Text> <Date> <Title>Date Field</Title> <Format>mm/dd/yyyy</Format> </Date>
Change
Type
from an element to an attribute and use XSD 1.1's Conditional Type Assignment. For an example, see How to make type depend on attribute value using Conditional Type Assignment. (XSD 1.1 only)Express your constraints via
xs:assertion
. (XSD 1.1 only)
Alternative #1 is prefered and can be easily implemented in both XSD 1.0 or XSD 1.1. It can also accommodate extension from a common base type.
来源:https://stackoverflow.com/questions/38595931/extend-xsd-type-based-on-element-value