Search code examples
xmlxsd

XSD: How to express constraint for attribute?


Let's say, I have the following element

<Employment type ="Full">
</Employment>

This is how I express the attribute

<xs:attribute name="Degree" type="xs:string" use="required" />

Now I'd like to express also the fact that the attribute can only have 2 values, i.e. Full and Part

So, I tried this

   <xs:attribute name="Degree" type="xs:string" use="required" >
        <xs:simpleType>
            <xs:restriction base="xs:string">
            </xs:restriction>
        </xs:simpleType>
    </xs:attribute>

I'm getting the error that xs:attribute cannot be present with either SimpleType or ComplexType.

How do I express that constraint?

Thank for helping.


Solution

  • Here's an XML Schema definition demonstrating an element with string content and an attribute with enumerated values:

    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               version="1.0">
    
      <xs:element name="Employment">
        <xs:complexType>
          <xs:simpleContent>
            <xs:extension base="xs:string">
              <xs:attribute name="Degree" use="required">
                <xs:simpleType>
                  <xs:restriction base="xs:string">
                    <xs:enumeration value="Full" />
                    <xs:enumeration value="Part" />
                  </xs:restriction>
                </xs:simpleType>
              </xs:attribute>
            </xs:extension>
          </xs:simpleContent>
        </xs:complexType>
      </xs:element>
    </xs:schema>
    

    Such that this XML instance would be valid:

    <Employment Degree="Part">string content</Employment>
    

    This XML instance would be invalid (missing attribute):

    <Employment>string content</Employment>
    

    And this XML instance would be invalid (illegal attribute value):

    <Employment Degree="asdf">string content</Employment>