Georgy Gobozov
Georgy Gobozov

Reputation: 13721

XSD: multiple types with same element name

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?

Upvotes: 6

Views: 9121

Answers (2)

Michael Kay
Michael Kay

Reputation: 163262

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.

Upvotes: 3

bdoughan
bdoughan

Reputation: 148977

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>

Upvotes: 6

Related Questions