xml - 如何在 XSD 架构中定义备用 XML 结构?

标签 xml xsd schema

如何在 xsd 架构中定义备用 XML 结构?例如,下一个结构是可选的:

<a>
  <b/>
  <c>
    <d/>
  </c>
</a>

<a>
  <c>
    <e/>
  </c>
</a>

在第一种情况下,如果要在“c”元素下找到“d”元素,则必须有“b”元素。在第二种情况下,如果“c”下有“e”,则不允许有“b”元素。所以我正在寻找这种解决方案:

<xsd:element name="a">
    <xsd:complexType>
        <xsd:all>

(

            <xsd:element name="b" type="whatever"/>
            <xsd:element name="c">
                <xsd:complexType>
                    <xsd:all>
                        <xsd:element name="d" type="whatever"/>
                    </xsd:all>
                </xsd:complexType>
            </xsd:element> )

) 或 (

            <xsd:element name="c">
                <xsd:complexType>
                    <xsd:all>
                        <xsd:element name="e" type="whatever"/>
                    </xsd:all>
                </xsd:complexType>
            </xsd:element>

)

        </xsd:all>
    </xsd:complexType>
</xsd:element>

我不想使用 choice 元素的原因是因为我正在为 XML 文档制作一个编辑器界面,而 choice 在我的例子中在编辑器界面中看起来很愚蠢。

最佳答案

解决方案是定义两个复杂类型来表示结构的每个“状态”。每种复杂类型都会对其中的嵌套元素应用不同的约束。然后,您可以简单地将这两种复杂类型分组为 xs:choice

下的项目

有点像

<?xml version="1.0" encoding="utf-16"?>
<xs:schema xmlns="http://NS.Schema1" targetNamespace="http://NS.Schema1" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Root">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="structure">
          <xs:complexType>
            <xs:choice minOccurs="1" maxOccurs="1">
              <xs:element name="a1" type="a1" />
              <xs:element name="a2" type="a2" />
            </xs:choice>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:complexType name="a1">
    <xs:sequence>
      <xs:element name="b" type="xs:string" />
      <xs:element name="c">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="d" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="a2">
    <xs:sequence>
      <xs:element name="c">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="e" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

但是,您不能为两种复杂类型使用相同的根元素名称。

关于xml - 如何在 XSD 架构中定义备用 XML 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6278922/

相关文章:

jpa - 管理@NamedNativeQuery 和模式

android - 检索字符串和字符串数组资源的区别?

python - 使用 BeautifulSoup 和 If 语句与 xml 文件交互

xml - 根据其他 XML 字段的值在 XSD 中设置 minOccurs 和 maxOccurs?

java - JAXB xsd 如何像引用一样使用数组成员

xml - 具有命名空间的 XML 属性的 XSD 语法

xml - 最好的 JDBC 数据源 bean 类

xml - 我应该如何使用 XML::Simple 处理 undefined reference ?

delphi - 我可以使用 xsd :complexContent with the Delphi XML Binding Wizard?

mysql - 用于选择美国多个州的模式设计,或 "all"