【问题标题】:XSD: Restrict only one child element to have specific valueXSD:仅限制一个子元素具有特定值
【发布时间】:2015-03-09 11:33:01
【问题描述】:

我有一个 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>

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

非常感谢任何帮助/想法。

【问题讨论】:

    标签: xml xsd


    【解决方案1】:

    您必须在 XSD 1.0 之外强制执行这样的约束,但您可以使用 xs:assertXSD 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

    【讨论】:

    • 谢谢。反正有没有断言?另外,主要处理器是否支持 XSD 1.1?我尝试在 Visual Studio 2013 中使用断言,但它不起作用。有什么免费工具可以让我根据 XSD 1.1 模式验证 XML 吗?
    • 正如我所提到的,如果您想在 XSD 中执行此操作,您将需要 XSD 1.1。有关支持 XSD 1.1 的处理器列表,请参阅this answer。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    相关资源
    最近更新 更多