XSD: How to derive a simpletype both to add a attribute to it and to restrict the acceptable value of it

前端 未结 2 833
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-15 01:49

for example To validate the following element:

 100 

The constraint I want on the text

相关标签:
2条回答
  • 2021-01-15 02:15

    It is not possible without adding a new type; you can't extend and restrict at the same time.

    0 讨论(0)
  • 2021-01-15 02:21

    Extending a simple type with attributes

    Inspired by Petru Gardea's answer to XSD custom type with attribute and restriction, I have come up with a solution that should work for you. Your element must be a complexType extending the restricted simpleType with an attribute:

    <!-- simple type that we want to extend with an attribute -->
    <xs:simpleType name="populationType">
        <xs:restriction base="xs:integer">
            <xs:minInclusive value="0"/>
            <xs:maxInclusive value="1000"/>
        </xs:restriction>
    </xs:simpleType>
    
    <!-- extending a simple content element with an attribute -->
    <xs:element name="population">
        <xs:complexType>
            <xs:simpleContent>
                <!-- populationType is a simple type -->
                <xs:extension base="populationType">
                    <xs:attribute name="class" type="xs:string" use="required"/>
                </xs:extension>
            </xs:simpleContent>
        </xs:complexType>
    </xs:element>
    

    Extending multiple types with the same set of attributes

    In addition, if you want to extend multiple types with the same set of attributes, you could use the xsd:attributeGroup as suggested in C. M. Sperberg-McQueen's answer to XSD: Adding attributes to strongly-typed “simple” elements:

    <!-- several types declare this set of attributes -->
    <xs:attributeGroup name="extensible"> 
        <xs:attribute name="att1" type="xs:string" />
        <xs:attribute name="att2" type="xs:string" />
    </xs:attributeGroup>
    
    <!-- simple type that we want to extend with attributes -->
    <xs:simpleType name="populationType">
        <xs:restriction base="xs:integer">
            <xs:minInclusive value="0"/>
            <xs:maxInclusive value="1000"/>
        </xs:restriction>
    </xs:simpleType>
    
    <!-- extending a simple content element with two 'inherited' attributes -->
    <xs:element name="population">
        <xs:complexType>
            <xs:simpleContent>
                <!-- populationType is a simple type -->
                <xs:extension base="populationType">
                    <xs:attributeGroup ref="extensible"/>
                </xs:extension>
            </xs:simpleContent>
        </xs:complexType>
    </xs:element>
    

    This would validate the following xml element:

    <population att1="AAA" att2="BBB">100</population >
    
    0 讨论(0)
提交回复
热议问题