How to mix extensions and restrictions in XSD complex type definitions

1.8k views Asked by At

I'm having problems creating complex type that is required to be non-(null|blank) and have a 'qualifier' attribute that is also non-(null|blank). This is what I have so far.

<xsd:complexType name="PRODUCT">
    <xsd:simpleContent>
        <xsd:extension base="xsd:string">
            <xsd:attribute name="Qualifier" type="xsd:string" use="required" />
        </xsd:extension>
        <xsd:restriction base="xsd:string">
            <xsd:minLength value="1"/>
        </xsd:restriction>
    </xsd:simpleContent>        
</xsd:complexType>
1

There are 1 answers

0
Mathias Müller On

It is impossible to have both extension and restriction in the same type definition. Define a simple type with the restriction, and then extend this custom type. You can use this simple type both for the element and attribute definition.

Please note that XML (and, by extension, if you forgive the pun, XML Schema) is case-sensitive. "qualifier" and "Qualifier" are not the same attribute names.

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:element name="PRODUCT" type="PRODUCTType"/>

    <xs:complexType name="PRODUCTType">
        <xs:simpleContent>
            <xs:extension base="restrictedType">
                <xs:attribute name="qualifier" type="restrictedType" use="required" />
            </xs:extension>
        </xs:simpleContent>        
    </xs:complexType>

    <xs:simpleType name="restrictedType">
            <xs:restriction base="xs:string">
                <xs:minLength value="1"/>
            </xs:restriction>
    </xs:simpleType>

</xs:schema>

The following XML document will be valid against the schema above:

<?xml version="1.0" encoding="UTF-8"?>
<PRODUCT qualifier="value">text</PRODUCT>

while documents like

<?xml version="1.0" encoding="UTF-8"?>
<PRODUCT qualifier="">text</PRODUCT>

or

<?xml version="1.0" encoding="UTF-8"?>
<PRODUCT qualifier="value"></PRODUCT>

will be invalid.