Tag Archives: XSD - Page 3

Validate both element and attribute with XSD

I have this XML snippet that I need to validate:

1<cars>
2  <car model="740GL">Volvo</car>
3</cars>

I want to validate both the attribute ‘model’ content and the element content ‘Volvo’. Here is one way of doing it (thank you Alex):

01<xsd:schema>
02:
03<xs:element name="car">
04  <xs:complexType>
05    <xs:simpleContent>
06      <xs:extension base="xsd:string">
07        <xs:attribute name="model" type="xsd:string"/>
08      </xs:extension>
09    </xs:simpleContent>
10  </xs:complexType>
11</xs:element>
12:
13</xsd:schema>

The base attribute will validate the element content ‘Volvo’ and the attribute type will validate the ‘model’

Validate XML element or attribute against multiple patterns in a XSD

Every now and then you need to validate an element or attribute agains multiple patterns.
Say an element is allowed to contain a date both in ‘YYYYnn’ format (where nn is the week number) and ‘seasonYY’ format. To solve this I use the following xsd pattern:

1<xsd:schema>
2:
3   <xs:simpletype name="mydate">
4       <xs:restriction base="xs:string">
5           <xs:pattern value="(19|20[0-9]{2}[0-5][0-9]) | (summer[0-9]{2}) | (winter[0-9]{2}) | (fall[0-9]{2}) | (spring[0-9]{2})"/>
6       </xs:restriction>
7   </xs:simpletype>
8:
9</xsd:schema>

The solution to my problem lies in the ‘|’ and parenthesis. I group the different patterns in parenthesis and separate the patterns with the OR-operator ‘|’. This way I can validate both syntaxes YYYYnn and seasonYY – only one needs to be true

There are of course other ways (shorter) to write the pattern but I choose this way because I believe it is easier to understand.