java - XSD 架构元素可以是两种类型之一

标签 java xml xsd jaxb schema

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

<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 is an element, and no child allowed error,第二个给出了“模型组中出现多个名为“food”的元素,并且具有不同的类型。”

此 XSD 是 java 有效负载对象的有效负载,其中具有: FoodInterface 食物。 Meat 和 Veggies 是该界面的枚举,如下所示:

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

架构中的肉类/蔬菜枚举:

<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.

最佳答案

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

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

由于您没有告诉我们肉类食品和素食食品这两种类型是什么,所以很难更具体地回答。您也没有明确说明您遇到的错误。

关于java - XSD 架构元素可以是两种类型之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58125177/

相关文章:

python - 带有请求库的机器人框架 CDATA xml

xml - 合并 Maximo 生成的 XSD?

XML 模式导致没有 namespace 的 xml 元素

java - 将 JTextField 添加到 JToolBar

java - transient 变量如何在 Worker 上可用

java - Elasticsearch : plain text file instead of JSON

java - 为什么 Hibernate SchemaUpdate 创建新字段而不是更新?

java - 无法使 XPath 与复杂的命名空间一起使用

php - 将对象显示为 HTML 和 XML

xsd - 在 xsd 模式中定义元素列表