How define several elements with same name, but different type in xsd:choice element?

xml, xsd

Solution

As earlier answers have already mentioned, you can do this easily enough in XSD 1.0 by using the `xsi:type` attribute instead of defining a new `ItemType` attribute with the same functionality.

XSD 1.1 includes a construct designed to make it easier to support cases like this one, for people who for whatever reason don't want to use `xsi:type` this way: conditional type assignment. Essentially it allows an element declaration to have simple sequence of XPath / typename pairs; the XPath expressions are evaluated in sequence and when one evaluates to true, the element is associated with the corresponding type. There are restrictions on the XPaths to prohibit looking ahead into the element's descendants or looking up or out into other parts of the XML document (the first helps keep it possible to know, as soon as a scan encounters a start-tag, which type to use for validating an element; the second helps keep validation context-free), so essentially the tests can only be tests on attribute values. Your example can be written thus:

<xs:element name="item">
  <xs:alternative test="@ItemType='SimpleMessage'" type="SimpleMessType"/>
  <xs:alternative test="@ItemType='SimpleMessage'" type="ComplexMessType"/>
  <xs:alternative type="xs:error"/>
</xs:element>

The third alternative ensures that one of your expected cases must be encountered, for the element to be valid. If it were omitted here, then if neither of the test expressions were true, the element would be assigned the declared type of `item`, in this case `xs:anyType`.

Problem

Is it possible in some way, to define an xsd scheme which could validate such xml: ``` <item_list> <item ItemType="SimpleMessage" Caption="Simplest message"/> <item ItemType="ComplexMessage" SomeAttr="value"> <item_data>some text</item_data> </item> </item_list> ``` Problem is that i havn't find any possibility to define smth like: ``` <xsd:element name="Items"> <xsd:complexType> <xsd:choice> <xsd:element name="item" type="SimpleMessType"/> <xsd:element name="item" type="ComplexMessType"/> </xsd:choice> </xsd:complexType> </xsd:element> ``` But i need to check, that SimpleMessage has no child elements or additional attrs :(

Original source