-->

XSD custom type with attribute and restriction

2019-02-24 02:57发布

问题:

I am developing an XSD document to validate XML Import files. Nearly all elements of the import file 'can' have an ID attribute (UPDATE). The UPDATE attribute must be limited to 4 possible values, so I have this pre-set type to use for the attribute restriction...

<xs:simpleType name="MyUpDir">
  <xs:restriction base="xs:string">
    <xs:enumeration value="OVERWRITE"/>
    <xs:enumeration value="ADDONLY" />
    <xs:enumeration value="NOERASE" />
    <xs:enumeration value="IGNORE" />
  </xs:restriction>
</xs:simpleType>

In addition to the attribute restrictions, each element's value is limited by a variety of pre-set custom types Example:

<xs:simpleType name="MyChar50">
  <xs:restriction base="xs:string">
    <xs:maxLength value="50" />
  </xs:restriction>
</xs:simpleType>

To combine the two, I know I can do it in-line for each element as follows:

<xs:element name="FullName">
  <xs:complexType>
    <xs:simpleContent>
      <xs:extension base="MyChar50">
        <xs:attribute name="UPDATE" type="MyUpDir" />
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
</xs:element>

The problem is that there are over 1000 elements in the import file, each having varying length/regEx/precision restrictions (roughly 20 custom types) as well as have the potential for the UPDATE attribute. Without the UPDATE attribute, I could do each element on its own line by using the custom types, greatly reducing the 'content' portion of the XSD. But from what I've read, it appears that to accomodate the custom types AND the potential for the attribute mentioned, I'm forced to use the expanded sample (last example) instead of being able to retain a single line for each such element. Is there not a way to minimize this further by creating a custom type that combines the two?

回答1:

I would think that you could do 20 custom types more (for a total of 40) and then use the appropriate ones (w/ or w/o attribute). In your case:

<xs:complexType name="MyChar50Attr"><!-- This one has attributes -->
    <xs:simpleContent>
        <xs:extension base="MyChar50">
            <xs:attribute name="UPDATE" type="MyUpDir"/>
        </xs:extension>
    </xs:simpleContent>
</xs:complexType>
<xs:element name="FullName" type="MyChar50Attr"/>