允许 XSD 日期元素为空字符串

Allow XSD date element to be empty string

我想允许元素为 xs:date 或空字符串。

这是我试过的 XML 模式:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
           xmlns:lp="urn:oio:ebst:diadem:lokalplan:1" 
           targetNamespace="urn:oio:ebst:diadem:lokalplan:1" 
           elementFormDefault="qualified" xml:lang="DA" 
           xmlns:m="urn:oio:ebst:diadem:metadata:1">
  <xs:import schemaLocation="../key.xsd" namespace="urn:oio:ebst:diadem:metadata:1" />
  <xs:element name="DatoVedtaget" type="lp:DatoVedtagetType" />
  <xs:complexType name="DatoVedtagetType">
    <xs:simpleContent>      
      <xs:extension base="xs:date">
        <xs:attribute ref="m:key" />
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:complexType name="DatoVedtagetTypeString">
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute ref="m:key" />
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
</xs:schema>

如果元素包含一个值,我希望它是 DatoVedtagetType,如果它是空的,我希望它是 DatoVedtagetTypeString。我如何在这个架构中实现这样的条件功能?

根据对该问题的评论,目标是让 DatoVedtaget 成为 xs:date 或为空。这是表达这种约束的一种方式:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:lp="urn:oio:ebst:diadem:lokalplan:1"
           xmlns:m="urn:oio:ebst:diadem:metadata:1"
           targetNamespace="urn:oio:ebst:diadem:lokalplan:1"
           elementFormDefault="qualified"
           xml:lang="DA">
  <xs:import schemaLocation="../key.xsd" namespace="urn:oio:ebst:diadem:metadata:1" />
  <xs:element name="DatoVedtaget" type="lp:DatoVedtagetType" />

  <xs:simpleType name="empty">
    <xs:restriction base="xs:string">
      <xs:enumeration value=""/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="dateOrEmpty">
    <xs:union memberTypes="xs:date lp:empty"/>
  </xs:simpleType>  

  <xs:complexType name="DatoVedtagetType">
    <xs:simpleContent>
      <xs:extension base="lp:dateOrEmpty">
        <xs:attribute ref="m:key" />
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>

</xs:schema>

我自己的首选解决方案是使用允许零次或一次出现的列表类型,而不是像@kjhughes 那样使用联合类型:

<xs:simpleType name="dateOrEmpty">
    <xs:list itemType="xs:date" maxLength="1"/>
</xs:simpleType> 

首选的一个原因是它的代码更少。另一个原因是,如果您正在编写模式感知 XSLT 或 XQuery 代码,则结果值更容易操作(原子化值的类型为 xs:date?联合类型)。