开发者

How to make restrictions on XML Schema Complex type?

I am reading the tutorials on w3cschools ( http://www.w3schools.com/schema/schema_complex.asp ) but they don't seem to mention how you could add restrictions on complex types.

Like for instance I have this schema.

<xs:element name="employee">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="firstname" type="xs:string"/>
      <xs:element name="lastname" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

now I want to make sure the firstname is no more then 10 characters long. How do I do this?

I tried to put in the simple type for the firstname but it says I can't do that since I am using a complex type.

So how do I put restrictions like that on the fil开发者_开发知识库e so the people who I give the schema to don't try to make the firstname 100 characters.


There are some restrictions you can have with XSD:

Let's say you want firstName no more than 10 characters long. You will use something like:

<xs:element name="employee">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="firstname">
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:minLength value="1"/>
            <xs:maxLength value="10"/>
          </xs:restriction>
        </xs:simpleType>
      </xs:element>
      <xs:element name="lastname" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

For more complex constraints, you will have to do some code-based checking I guess.


<xs:element name="employee">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="firstname">
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:maxLength value="10"/>
          </xs:restriction>
        </xs:simpleType>
      </xs:element>
      <xs:element name="lastname" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

Is this solving your problem?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜