Category Archives: Misc - Page 13

Validate pattern OR nothing in XSD

Say you have a XML like this:

:
20110506
:

Where <date> is allowed to be empty OR follow pattern ’19|20[0-9]{2}[0-1][0-9][0-3][0-9]’. How do you validate it? The solution is too simple and that is why I didn’t figure it out myself. I googled it and soon found a much smarter guy than me that said to do it like this:


:

    
                   
            <xs:pattern value="(19|20[0-9]{2}[0-1][0-9][0-3][0-9])|"/>
        
    

:

This validates YYYYMMDD type dates and also validate an empty date tag. The solution lies in the last OR operand ‘|’. You see, either the left one (the pattern) is true or the right one (which is empty). Cleaver ah? I certainly thinks soo

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.