views:

958

answers:

4

Hi,

I have a question regarding adding restriction in my xml schema(xsd). I have a complex-type like:

<-->xsd:complexType name="xxx"> <-->xsd:attribute/> ..... <-->/xsd:complexType>

I have many attributes in this complex-type, and few of them are of string type. Now I want those string type attributes to be restricted to y no. of chars, how do I add this restriction?

Thanks! -Ankush

+4  A: 

You need to create a simple type like so:

  <xs:simpleType name="LimitedString">
    <xs:restriction base="xs:string">
      <xs:maxLength value="50" />
    </xs:restriction>
  </xs:simpleType>

and then use this new type in your schema:

  <xs:complexType name="test">
    <xs:sequence>
      <xs:element name="abc" type="xs:String" />
    </xs:sequence>
    <xs:attribute type="LimitedString" name="myattr" />
  </xs:complexType>

Marc

marc_s
+2  A: 

You can restrict the string to a number of chars like this:

<xs:simpleType name="threeCharString">
  <xs:annotation>
    <xs:documentation>3-char strings only</xs:documentation>
  </xs:annotation>
  <xs:restriction base="xs:string">
    <xs:length value="3"/>
  </xs:restriction>
</xs:simpleType>

The xs:length in the above limits the length of the string to exactly 3 chars. You can also use xs:minLength and xs:maxlength, or both.

You can provide a pattern like so:

<xs:simpleType name="fourCharAlphaString">
  <xs:restriction base="xs:string">
    <xs:pattern value="[a-zA-Z]{4}"/>
  </xs:restriction>
</xs:simpleType>

The above says, 4 chars, of any of a-z, A-Z. The xs:pattern is a regular expression, so go to town with it.

You can restrict the string to a particular set of strings in this way:

<xs:simpleType name="iso3currency">
  <xs:annotation>
    <xs:documentation>ISO-4217 3-letter currency codes. Only a subset are defined here.</xs:documentation>
  </xs:annotation>
  <xs:restriction base="xs:string">
    <xs:length value="3"/>
    <xs:enumeration value="AUD"/>
    <xs:enumeration value="BRL"/>
    <xs:enumeration value="CAD"/>
    <xs:enumeration value="CNY"/>
    <xs:enumeration value="EUR"/>
    <xs:enumeration value="GBP"/>
    <xs:enumeration value="INR"/>
    <xs:enumeration value="JPY"/>
    <xs:enumeration value="RUR"/>
    <xs:enumeration value="USD"/>
  </xs:restriction>
</xs:simpleType>
Cheeso
the xs:length however requires the string to be the defined exact length - it doesn't just limit the maximum length.
marc_s
good point! ....
Cheeso
A: 

you can always define the maximal length of a string in xsd. Just add the attribute manLength resp. minLength.

Luixv
A: 

How can I mention more than one allowable length property?

<xs:simpleType name="threeOrSevenCharString">
   <xs:restriction base="xs:string">
      <xs:length value="3"/>
      *<xs:length value="7"/>*
   </xs:restriction>
</xs:simpleType>

Will the above code pass for values of 3 or 7 character length strings? If it doesn't what is the right syntax to achieve it?

Mandai