XSD 架构元素可以是两种类型中的一种

XSD Schema element can be either of Two Types

我环顾四周,是否真的没有简单的方法可以让一个元素成为两种可能的类型?我尝试了以下解决方法。

<xs:element name="food">
  <xs:complexType>
     <xs:choice>
       <xs:element name="meat" type="meatFoods"/>
       <xs:element name="veggies" type="veggieFoods"/>
     </xs:choice>
  </xs:complexType>
</xs:element>
food cannot have character [children], because the type's content type is element-only.

并且:

<xs:choice>
  <xs:sequence>
    <xs:element name="food" type="meatFoods"/>
  </xs:sequnce>
  <xs:sequence>
    <xs:element name="food" type="veggieFoods"/>
  </xs:sequence>
</xs:choice>

给出关于同名不同类型的错误

并且:

<xs:complexType name="MeatOrVeggies">
  <xs:choice>
    <xs:element name="meat" type="meatFoods"/>
    <xs:element name="veggies" type="veggieFoods"/>
  </xs:choice>
</xs:complexType>
<xs:element name="food" type="MeatOrVeggies"/>
food cannot have character [children], because the type's content type is element-only.

这些都会抛出某种错误。最后一个给的是food是一个元素,不允许child出错,第二个给的是"Multiple elements with name "food",模型组中出现了不同的类型。"

此 XSD 是 java 有效负载对象的有效负载,它具有: FoodInterface food。 Meat 和 Veggies 是该接口的枚举,如下所示:

public enum Meat implements FoodInterface{
   Chicken,
   Beef,
   Pork
}

Meat/Veggie 架构中的枚举:

<xs:simpleType name="meatFoods">
  <xs:restriction base="xs:string">
    <xs:enumeration value="chicken"/>
    <xs:enumeration value="beef"/>
    <xs:enumeration value="pork"/>
  </xs:restriction>
</xs:simpleType>

<xs:simpleType name="veggieFoods">
  <xs:restriction base="xs:string">
    <xs:enumeration value="spinach"/>
    <xs:enumeration value="broccoli"/>
    <xs:enumeration value="tomato"/>
  </xs:restriction>
</xs:simpleType>
Thanks in advance.

"...联合元素将简单类型定义为来自指定简单数据类型的值的集合(联合)..." 在这里查看:https://www.w3schools.com/xml/el_union.asp

如果类型是简单类型,请使用联合类型。

如果类型是复杂类型,则使用xs:choice:但生成的内容模型必须是明确的(即,您遇到的第一个元素必须告诉您选择哪个分支)。

由于您没有告诉我们 meatFoods 和 veggieFoods 这两种类型是什么,因此很难回答得更具体。您也没有明确说明您遇到的错误。