Extend XSD Type based on element value?

2019-01-29 00:20发布

问题:

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

  1. Redesign your XML. Rather than have a generic Field element with a generic Type 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>
    
  2. 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)

  3. 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.



标签: xml xsd xsd-1.1