【问题标题】:Require either both attributes or none to be present by XML schema要求 XML 模式同时存在或不存在两个属性
【发布时间】:2020-01-22 12:23:46
【问题描述】:

我有一个可能看起来像这样的元素:

<MyElement start="12.5. 2020" end="6.6 2020" info="Hello world!"/>

还有这个:

<!-- This element still can contain useful info, but is not time-bound -->
<MyElement info="42" />

所以我想设置节点的定义,以便必须存在非属性或两个属性。到目前为止,我只是使用文档来记录需求,但如果它直接在架构中会更好:

<xsd:complexType name="MyElement">
  <xsd:attribute name="start" type="MyDate" use="optional">
    <xs:annotation>
      <xs:documentation>end date must also be present!</xs:documentation>
    </xs:annotation>
  </xsd:attribute>
  <xsd:attribute name="end" type="MyDate" use="optional">
    <xs:annotation>
      <xs:documentation>start date must also be present!</xs:documentation>
    </xs:annotation>
  </xsd:attribute>
  <xsd:attribute name="info" type="xsd:string" use="required" />
</xsd:complexType>

【问题讨论】:

    标签: xml xsd xsd-validation xml-validation


    【解决方案1】:

    XSD 1.0

    您的约束不能单独在 XSD 1.0 中强制执行。

    XSD 1.1

    您的约束可以在 XSD 1.1 中使用 xsd:assert 强制执行:

        <xsd:assert test="(@start and @end) or (not(@start) and not(@end)) "/>
    

    在上下文中显示:

    <?xml version="1.0" encoding="UTF-8"?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
      xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" 
      elementFormDefault="qualified"
      vc:minVersion="1.1">
      <xsd:complexType name="MyElement">
        <xsd:attribute name="start" type="xsd:string" use="optional">
          <xsd:annotation>
            <xsd:documentation>end date must also be present!</xsd:documentation>
          </xsd:annotation>
        </xsd:attribute>
        <xsd:attribute name="end" type="xsd:string" use="optional">
          <xsd:annotation>
            <xsd:documentation>start date must also be present!</xsd:documentation>
          </xsd:annotation>
        </xsd:attribute>
        <xsd:attribute name="info" type="xsd:string" use="required" />
    
        <xsd:assert test="(@start and @end) or (not(@start) and not(@end)) "/>
    
      </xsd:complexType>
      <xsd:element name="MyElement" type="MyElement"/>
    </xsd:schema>
    

    【讨论】:

    • 这真的很酷。你碰巧知道这有多受支持吗?
    • 不幸的是不是普遍的。撒克逊人有(Java 和 .NET); Xerces 确实(Java);主要的 XML 编辑器都会这样做。大多数其他库没有。
    猜你喜欢
    • 1970-01-01
    • 2012-08-19
    • 2023-02-10
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    相关资源
    最近更新 更多