Question

i have a problem in below xsd schema how can i restrict comma separated string to only one character like this

    <status>A,B,C,D</status> 

currently i am using below code to create comma separated list of string.

    <xs:simpleType name="order">
<xs:annotation>
  <xs:documentation>
  Comma-separated list of anything
  </xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
  <xs:pattern value="[^,]+(,\s*[^,]+)*"/>
</xs:restriction>

Was it helpful?

Solution

Use

    <xs:element name="status">
    <xs:simpleType>
      <xs:restriction base="xs:string">
        <xs:pattern value="((([A-Z][,]+)+)([A-Z]?))|([A-Z]))"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:element>

to validate:

  <status>A</status>
  <status>A,</status>
  <status>A,B</status>
  <status>A,B,C,D</status>
  <status>A,B,C,D,</status>

and avoid

  <status>AA</status>
  <status>AA,</status>
  <status></status>
  <status>AAAA,BBBB,CCCC,DDDD,</status>

OTHER TIPS

Similar to Navin Rawat's answer, just different (and simpler) regex:

<xs:element name="status">
    <xs:simpleType>
        <xs:restriction base="xs:string">
            <xs:pattern value="[A-Z](,[A-Z])*"/>
        </xs:restriction>
    </xs:simpleType>
</xs:element>

Although @Navin Rawat's answer allows the use of commas, it is probably not the best/most XML solution to your problem.

A "better" solution, would be to use an XML list, as in the following schema code:

<xs:schema>
<xs:simpleType name="character">
  <xs:restriction base="xs:string">
    <xs:maxLength value="1" />
  </xs:restriction>
</xs:simpleType>
<xs:simpleType name="order">
  <xs:annotation>
    <xs:documentation>
    Space-separated list of single characters
    </xs:documentation>
  </xs:annotation>
  <xs:list itemType="character" />
</xs:simpleType>
</xs:schema>

As you can see, is uses a xs:restriction, rather than a regular expression, to enforce the length of each string being 1. The only drawback is that it requires the strings to be whitespace delineated, rather than comma-separated.

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