XSD:限制只有一个子元素具有特定值

XSD: Restrict only one child element to have specific value

我有一个 XML 上面写着

<Options>
  <option1>Y</option1>
  <option2>N</option2>
  <option3>N</option3>
</Options>

我想确保(选项的)只有一个子元素的值为 Y,以便上面的 XML 有效但下面的无效。

<Options>
  <option1>Y</option1>
  <option2>Y</option2>
  <option3>N</option3>
</Options>

我尝试了唯一性和参照完整性,但无法解决。

非常感谢 help/idea。

你必须在 XSD 1.0 之外强制执行这样的约束,但你可以使用 xs:assert 来强制执行 XSD 1.1:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified" 
  elementFormDefault="qualified" 
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
  vc:minVersion="1.1">

  <xs:element name="Options">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="option1"/>
        <xs:element name="option2"/>
        <xs:element name="option3"/>
      </xs:sequence>
      <xs:assert test="count(* = 'Y') = 1"/>
    </xs:complexType>
  </xs:element>
 </xs:schema>

或者,为了避免分别命名每个 option:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified" 
  elementFormDefault="qualified" 
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
  vc:minVersion="1.1">

  <xs:element name="Options">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="option" maxOccurs="unbounded" />
      </xs:sequence>
      <xs:assert test="count(option = 'Y') = 1"/>
    </xs:complexType>
  </xs:element>
 </xs:schema>

如果需要,当然也可以将选项限制为 YN