首页 > 解决方案 > 要求 XML 模式同时存在或不存在两个属性

问题描述

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

<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>

标签: xmlxsdxsd-validationxml-validation

解决方案


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>

推荐阅读