xml – 定义一个XSD元素,该元素可以是dateTime或带有属性的空

前端之家收集整理的这篇文章主要介绍了xml – 定义一个XSD元素,该元素可以是dateTime或带有属性的空前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的问题与 this one几乎完全相同,但对于xs:dateTime类型而不是用户定义的元素.

我的XML中的一个元素(我没有创建)可能如下所示:

  1. <parent>
  2. ...
  3. <start>2012-01-01T00:00:00.000</start>
  4. <end>2013-01-01T00:00:00.000</end>
  5. ...
  6. </parent>

-要么-

  1. <parent>
  2. ...
  3. <start reference="a string" />
  4. <end reference="a string" />
  5. ...
  6. </parent>

换句话说,在父元素中,“start”和“end”字段可以包含xs:dateTime值,或者为空但具有“reference”属性(任一字段可能是父元素中的一个或另一个,它们不一定既是参考,也不一定是dateTime).我已尝试过各种方法在XSD中表示这一点,但还没有找到解决方案.我最接近的是(摘自更大的XSD):

  1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  2. <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  3. <xs:complexType name="DateOrRef">
  4. <xs:simpleContent>
  5. <!-- <xs:extension base="xs:dateTime"> This does not validate-->
  6. <xs:extension base="xs:string">
  7. <xs:attribute type="xs:string" name="reference" use="optional"/>
  8. </xs:extension>
  9. </xs:simpleContent>
  10. </xs:complexType>
  11. <xs:complexType name="parent">
  12. <xs:sequence>
  13. <xs:element minOccurs="0" name="start" type="DateOrRef" />
  14. <xs:element minOccurs="0" name="end" type="DateOrRef" />
  15. </xs:sequence>
  16. </xs:complexType>
  17. </xs:schema>

它确实验证,但不限制节点内容为xs:dateTime值.如果我将扩展基类型更改为xs:dateTime而不是注释掉的xs:string,则空元素将不再验证,因为不允许dateTime类型为空.

我如何构建XSD以将这些字段验证为xs:dateTime而不是xs:string?

1您可以声明元素为nillable(由Ben建议).

2您可以声明一个简单类型,它是xs:dateTime和空字符串的并集.如果我们分阶段建立它,这是最容易遵循的.首先,声明一个名为simple的类型,其唯一值为空字符串:

  1. <xs:simpleType name="empty-string">
  2. <xs:restriction base="xs:string">
  3. <xs:enumeration value=""/>
  4. </xs:restriction>
  5. </xs:simpleType>

然后声明一个union类型,其成员是xs:dateTime和empty-string:

  1. <xs:simpleType name="dateTime-or-nothing">
  2. <xs:union memberTypes="xs:dateTime empty-string"/>
  3. </xs:simpleType>

然后使用dateTime-or-nothing作为扩展步骤的基础:

  1. <xs:complexType name="DateOrRef">
  2. <xs:simpleContent>
  3. <xs:extension base="dateTime-or-nothing">
  4. <xs:attribute type="xs:string"
  5. name="reference"
  6. use="optional"/>
  7. </xs:extension>
  8. </xs:simpleContent>
  9. </xs:complexType>

如果当且仅当元素没有内容时才会出现引用属性,那么您将需要一个XSD 1.1断言(或辅助Schematron模式,或应用层的临时验证代码). XSD内容模型可以很容易地说您必须具有dateTime或引用,但前提是每个选项都由子元素表示.

猜你在找的XML相关文章