Question

I've got an XSD file that is used to validate client-submitted XML and one of the fields they can submit is an xs:base64Binary type and are expected to be jpg or gif images. Frequently images will be submitted that are either of an unwanted type (.PNG, .TGA, .PSD) or are ridiculously large (greater than 10MB each)

I've tried restricting the length of the content, but every time I try to switch the content type of my element to complexContent and add restrictions, the xsd file fails validation because xs:base64Binary is of simpletype

The element is quite simplistic

<xs:element name="itemimage">
    <xs:annotation>
        <xs:documentation>Item picture in jpeg or gif format</xs:documentation>
    </xs:annotation>
    <xs:complexType>
        <xs:simpleContent>
            <xs:extension base="xs:base64Binary">
                <xs:attribute name="imgdescription" type="xs:string" use="optional"/>
            </xs:extension>
        </xs:simpleContent>
    </xs:complexType>
</xs:element>

`

Is it possible to restrict based on length of the image or by pattern matching the first few bytes to base64 gif or jpeg images?

Was it helpful?

Solution

It isn't possible to do this with xs:restriction as you mention, but you can do this with xs:assert elements and XPath 2.0 functions.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="itemimage">
    <xs:annotation>
      <xs:documentation>Item picture in jpeg or gif format</xs:documentation>
    </xs:annotation>
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:base64Binary">
          <xs:attribute name="imgdescription" type="xs:string" use="optional"/>
          <!-- Crudely check the base64 string length -->
          <xs:assert test="string-length(.) lt 2048"/>
          <!-- Matching on the start of a JPEG sequence -->
          <xs:assert test="matches(., '/9j/')"/>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

Your mileage may vary on how well this works, but it's a start.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top