Tag Archives: XSD - Page 3

Validate both element and attribute with XSD

I have this XML snippet that I need to validate:


  Volvo

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


:

  <xs:complexType>
    <xs:simpleContent>
      
        <xs:attribute name="model" type="xsd:string"/>
      
    </xs:simpleContent>
  </xs:complexType>

:

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:


:
   
       
           <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})"/>
       
   
:

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.