注意正如 Serge 指出的那样,这个答案是不正确的。
使用 xerces 进行测试会出现此错误:type.xsd:3:21: cos-element-consistent: Error for type '#AnonType_productinfo'. Multiple elements with name 'informationset', with different types, appear in the model group. cos-element-consistent 的规范中有更多详细信息。
但是有一个解决方案,类似于下面 Marc 的回答,但仍然使用类型。如果它们在由其他类型扩展的超类型的 minOccurs/maxOccurs 列表中,则可能会多次出现具有不同类型的相同内容。也就是说,就像 java 或 C# 中的多态类列表一样。这克服了上面的问题,因为虽然该元素名称可以在 xml 中出现多次,但它在 xsd 中只出现一次。
这里是示例 xsd 和 xml - 这次用 xerces 进行了测试!:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="productinfo">
<xs:complexType>
<xs:sequence>
<xs:element name="informationset" type="supertype" minOccurs="2" maxOccurs="2"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="supertype">
</xs:complexType>
<xs:complexType name="Manufacturer">
<xs:complexContent>
<xs:extension base="supertype">
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Ingredients">
<xs:complexContent>
<xs:extension base="supertype">
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:schema>
<productinfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<informationset xsi:type="Manufacturer"></informationset>
<informationset xsi:type="Ingredients"></informationset>
</productinfo>
注意:您无法控制不同类型的顺序,或每种类型出现的次数(每种可能出现一次、多次或根本不出现) - 就像java 或 C# 中的多态类列表。但是您至少可以指定整个列表的确切长度(如果您愿意的话)。
例如,我已将上面的示例限制为恰好两个元素,但未设置顺序(即 Manufacturer 可能是第一个,或者 Ingredients 可能是第一个);并且未设置重复次数(即它们都可以是制造商,或两者都是成分,或两者之一)。
您可以使用 XML Schematype,如下所示:
<productinfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<informationset xsi:type="Manufacturer"></informationset>
<informationset xsi:type="Ingredients"></informationset>
</productinfo>
XSD 为每个定义了单独的复杂类型:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="productinfo">
<xs:complexType>
<xs:sequence>
<xs:element name="informationset" type="Manufacturer"/>
<xs:element name="informationset" type="Ingredients"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="Manufacturer">
</xs:complexType>
<xs:complexType name="Ingredients">
</xs:complexType>
</xs:schema>
这是xsi:type 的特例。一般来说,不要以为可以在同名元素中指定属性有不同的值,因为它们是同一个元素的不同定义。
我不是 100% 清楚确切的原因 - 有人知道规范的相关部分吗?