`
lizhengjun
  • 浏览: 44363 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

在XML Schema中定义允许带空值的元素

阅读更多
提问:

我的一个XML文档中,有一个元素如果带空值就会报错,该元素在Schema中是定义的decimal类型,报错说:
is not a valid value for 'decimal'.

我尝试使用nillable="true"在Schema中对该元素进行申明,但仍然无法解决。

解答:

在元素中使用nillable="true"进行申明,还只是完成一半的工作。您还需要往XML文档中的空元素中添加xsi:nil="true"。例如,您在Schema中有如下定义:
<xs:element name="foo" type="xs:decimal" nillable="true" />

XML实例文档中就应该像下面这个样子:
<foo>12.5</foo>
<foo xsi:nil="true" />

但是像下面这样写就不行了:
<foo>bar</foo>
<foo />

如果您不想使用xsi:nil来标记元素,那么就应该定义一个新的数据类型,使该类型既可以容纳decimal类型的数据,又可以容纳空字符串数据,就像下面这个样子:
<xs:simpleType name="decimal-or-empty">
  <xs:union memberTypes="xs:decimal empty-string" />
</xs:simpleType>

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

<xs:element name="foo" type="decimal-or-empty" />

然后在xml实例文档中像下面这种写法才能通过验证:
<foo>12.5</foo>
<foo />

但是下面的写法却是错误的了。
<foo>bar</foo>


原文地址:
http://xsd.stylusstudio.com/2003May/post03006.htm

分享到:
评论
Global site tag (gtag.js) - Google Analytics