为必须至少有一个子元素的元素指定类型

Specify type for an element that must have at least one child element

元素 elements 必须至少包含元素 element1element2,但每个元素最多一次。为此,我指定了以下 XML 架构:

<?xml version="1.0" encoding="UTF-8"?> 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
   <xs:element name="elements" type ="elementsType"/>
   <xs:complexType name="elementsType">
      <xs:choice>
         <xs:sequence>
            <xs:element name="element1" type="xs:string" minOccurs="0"/>
            <xs:element name="element2" type="xs:double"/>
         </xs:sequence>
         <xs:element name="element1" type="xs:string"/>
      </xs:choice>
   </xs:complexType>
<xs:schema/>

此 XML 架构的验证给出了 "Unique Particle Attribution" 违规错误:

cos-nonambig: element1 and element1 (or elements from their substitution group) violate "Unique Particle Attribution". During validation against this schema, ambiguity would be created for those two particles.

为什么?

您的 XSD 违反唯一粒子属性的原因是由于 xs:choice 中关于 element1 是否应该与第一或第二选择可能性相关联的歧义。

您可以避免违规,并且仍然需要至少 element1element2 之一使用 XSD 1.1 的断言:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" elementFormDefault="qualified"
  vc:minVersion="1.1">
  <xs:element name="elements" type ="elementsType"/>
  <xs:complexType name="elementsType">
    <xs:sequence>
      <xs:element name="element1" type="xs:string" minOccurs="0"/>
      <xs:element name="element2" type="xs:double" minOccurs="0"/>
    </xs:sequence>
    <xs:assert test="count(*) > 0"/>
  </xs:complexType>
</xs:schema>

更新

I don't understand why there is a ambiguity. If a instance contains element1 and element2 or only element2 the first choice is only possible. Otherwise, if there is only a element2, the second choice applies only.

假装你是一个验证解析器,你遇到了 element1。您将不知道是将它与 xs:choice 的第一个分支还是第二个分支相关联,因此会产生歧义。当然,您可以向前看一级并解决歧义,但是您应该向前看多远? XSD 建议说,在这些情况下,您作为验证解析器根本不必向前看。因此,你作为验证器解析器的工作更容易(但你作为 XSD 作者的工作有点困难)。