开发者

How do I require that an element contain character data using XML Schema

If I have an xml document, for example:

<colors>  
    <color1>1452</color1>  
    <color2></color2>  
    <color3></color3>  
</colors>

I want to define in an XML schema, that the color1 element must contain a value of type int, be non null, and non empty. So the above example would be valid, but if color1 was empty like color2 and color3, it would fail. I've searched around but cannot seem to find a clean way to require that an element be populated with a valu开发者_JS百科e. Am I missing something really obvious?


You need to define the type for the element in your schema as follows:

<xs:element name="color" type="xs:integer"/>

To constrain the length of the element, use xs:restriction as follows.

<xs:element name="color">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:minLength value="5"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>

Notice that I used a string to represent the type. Off hand, I'm not sure if you can use minLength with an integer, but you can use a regular expression with xs:pattern.


Here is how you would do type-checking:

<xs:element name="lastname" type="xs:string"/>
<xs:element name="age" type="xs:integer"/>
<xs:element name="dateborn" type="xs:date"/>

So in your case, you'd want type="xs:integer"

The different restrictions you can actually do are quite extensive, like regular expressions and min and max integer values. More info here.

Edit: And here is a bit more info on the different numeric types you may want to specify instead of just integer.


for attributes, the schema should have:

<... use="required" type="..."/>

for elements:

<xs:element minOccurs="1"/>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜