Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSD: multiple types with same element name

Tags:

types

xml

xsd

I am using xsd for xml validation. I need to describe one element with two types.

   <xsd:choice>
                            <xsd:element name="num" minOccurs="1" type="xsd:integer" fixed="0"/>
                            <xsd:element name="num" minOccurs="1" type="xsd:positiveInteger"/>
</xsd:choice>

When I validate xml with num = 0 validation is successful, but when I validate xml with num value = 1 or greater validation fails with error. How to describe this case correct?

like image 644
Georgy Gobozov Avatar asked May 24 '11 10:05

Georgy Gobozov


2 Answers

I would use xs:nonNegativeInteger for this use case:

<xs:element name="num" type="xs:nonNegativeInteger">

If you want an element to support multiple types you can use a union:

<xs:element name="num" default="0">
  <xs:simpleType>
    <xs:union memberTypes="xs:integer xs:positiveInteger" />
  </xs:simpleType>
</xs:element>
like image 70
bdoughan Avatar answered Sep 28 '22 19:09

bdoughan


You can't have two element particles in the same complex type with the same name and different types (this rule is called "Element Declarations Consistent" if you want to look it up). Part of the reason is that XSD is used not only for validation, but also for data typing, e.g. in Java data binding.

But I think what you are looking for here is a union type.

like image 22
Michael Kay Avatar answered Sep 28 '22 19:09

Michael Kay