Search code examples
xmlvalidationxsdrestriction

XSD for simplecontent with attribute and text


How can i validate the text length of the element that has an attribute. E.g:

    <sport code="FB">Football</sport>

Now i need to restrict the possible values of the code attribute(like "FB", "BB", "TT") and also i need to restrict the possible values and length of the text("Football", "BasketBall", "TableTennis") and also the maximum length of these text("Football", "BasketBall", "TableTennis") can be 20.

I tried with

<complexType name="sport">
  <simpleContent>
    <extension base="string">
        <attribute name="code" type="code" />
    </extension>
  </simpleContent>
</complexType>
<simpleType name="code">
    <restriction base="string">
        <enumeration value="FB" />
        <enumeration value="BB" />
        <enumeration value="TT" />
    </restriction>
</simpleType>

But i cant validate the length of the text "Foolball" (also the possible values) Can you please help about how to validate both the code and the text. Thanks


Solution

  • I had this identical question, and was hopeful when I saw there was an accepted answer. However, that answer is exactly what I tried, but I was getting a schema invalid error. Apparently, you can't restrict simpleContent within a complexType, only extend it. Additionally, you can't have both an attribute and simpleContent within a complexType. Searching for examples in books around the office, I came up with a fix, which I adapted to this question in case someone else has this problem in the future:

    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                xmlns:sp="http://www.ckhrysze.net/sports/1.0"
                targetNamespace="http://www.ckhrysze.net/sports/1.0"
            >
    
      <xsd:element name="sports">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="sport" type="sp:sportType" minOccurs="1" maxOccurs="unbounded" />
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    
      <xsd:complexType name="sportType">
        <xsd:simpleContent>
          <xsd:extension base="sp:sportEnumeration">
            <xsd:attribute name="code" type="sp:codeEnumeration" />
          </xsd:extension>
        </xsd:simpleContent>
      </xsd:complexType>
    
      <xsd:simpleType name="sportEnumeration">
        <xsd:restriction base="xsd:string">
          <xsd:enumeration value="Football" />
          <xsd:enumeration value="Basketball" />
        </xsd:restriction>
      </xsd:simpleType>
    
      <xsd:simpleType name="codeEnumeration">
        <xsd:restriction base="xsd:string">
          <xsd:enumeration value="FB" />
          <xsd:enumeration value="BB" />
        </xsd:restriction>
      </xsd:simpleType>
    
    </xsd:schema>