【问题标题】:How to declare a non-string element as having optional content in XML Schema如何在 XML Schema 中将非字符串元素声明为具有可选内容
【发布时间】:2010-11-26 23:10:12
【问题描述】:

我见过XML Schema element with attributes containing only text,但我有一个元素是 xs:dateTime。

我正在尝试为其编写架构的文档如下所示:

<web-campaigns>
  <web-campaign>
    <id>1231</id>
    <start-at nil="true"/>
  </web-campaign>
  <web-campaign>
    <id>1232</id>
    <start-at>2009-08-08T09:00:00Z</start-at>
  </web-campaign>
</web-campaigns>

有时 xs:dateTime 元素有内容,有时没有。

到目前为止我所拥有的(尚未验证)是:

<xs:element name="start-at">
  <xs:complexType mixed="true">
    <xs:simpleContent>
      <xs:extension base="xs:dateTime">
        <xs:attribute name="nil" default="false" type="xs:boolean" use="optional" />
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
</xs:element>

如果我将 xs:dateTime 替换为 xs:string,我可以很好地验证文档,但我真的想要一个 xs:dateTime,以向消费者指示该元素中的内容。我也尝试过使用/不使用 mixed="true",但无济于事。

如果有影响,我会使用 xmllint(在 Mac OS X 10.5 上)和 XML Schema Validator 进行验证

【问题讨论】:

    标签: xsd


    【解决方案1】:

    你需要

    <xs:element name="start-at" minOccurs="0">
    

    混合模式与您的情况无关,您不需要。默认情况下,minOccurs="1",即该元素是必需的。

    使用 minOccurs="0",您可以指定带有内容的元素,或者根本不指定。如果您希望能够允许&lt;start-at/&gt;,那么您不能使用 xs:dateTime。

    【讨论】:

      【解决方案2】:

      您可以将自己的类型定义为类型的联合。

      1/ 将“空”类型定义为只允许“” ähm nothing 的字符串:)

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

      2/接下来定义一个允许日期和空的类型

      <xs:simpleType name="empty-dateTime">
        <xs:union memberTypes="xs:dateTime empty"/>
      </xs:simpleType>
      

      3/ 将所有可以为空的日期时间元素声明为 type="empty-dateTime"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-04
        • 1970-01-01
        • 2021-09-07
        • 1970-01-01
        • 2018-08-08
        • 1970-01-01
        相关资源
        最近更新 更多