【问题标题】:Allow XSD date element to be empty string允许 XSD 日期元素为空字符串
【发布时间】:2016-01-25 09:41:26
【问题描述】:

我想允许一个元素是 xs:date 或空字符串。

这是我尝试过的 XML Schema:

<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 还是空的一种复杂的方式吗?
  • 如果可能的话是的

标签: c# xml xsd schema


【解决方案1】:

根据问题,目标是让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>

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 好吧,如果我再考虑一年,我可能也会想出这个xs:list 的想法。 :-) 说真的:我喜欢这种方法。很好的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 2014-06-21
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多