我需要将一个简单的元素类型设置为整数,但同时允许它为空。如果为空并且空字段不是整数,则会出现错误。如何解决这个问题?
<xsd:element name="weight" type="xsd:integer"/>
你需要做的是在同一元素上设置限制,并对它们执行联合操作,例如以下示例:
<xs:element name="job_code">
<xs:simpleType>
<xs:union>
<xs:simpleType>
<xs:restriction base='xs:string'>
<xs:length value="0"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType>
<xs:restriction base='xs:integer' />
</xs:simpleType>
</xs:union>
</xs:simpleType>
</xs:element>
通过使用这个限制,您告诉XML验证允许任何整数值,并在元素为空时允许该元素。
我们可以通过创建一个SimpleType来实现这一点
<xs:simpleType name="NullOrInteger">
<xs:restriction base="xs:string">
<xs:pattern value="\d*|\s{0}" />
</xs:restriction>
</xs:simpleType>
将NullOrInteger作为类型添加到您希望对整数或空值进行限制的位置。
例如:
<xs:element name="null_or_int" type="NullOrInteger" />
<xsd:element name="weight" type="xsd:integer" nillable="true"/>
</xsd:complexType>
</xsd:schema> - leanne<weight xsi:nil="true"></weight>
。没有该属性的空元素仍然无法通过验证。 - Burkart<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!-- Sample XML generated by QTAssistant (http://www.paschidev.com) -->
<products xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<product>
<weight xsi:nil="true"/>
</product>
</products>
请尝试以上方法,应该可以解决问题;很可能您忘记添加xsi:nil属性了。此外,请确保weight元素没有字符作为其子元素(空格也是不可接受的)。如果您必须传递一些字符而不是整数,则必须定义联合类型以允许两者。
我通过搜索如何使用xsd模式使属性成为可空整数,并基于生成的JAXB类得出了这个答案。我在这里没有找到答案,所以在发现答案后,我决定分享它。以下xsd部分将生成一个不可空类型的int(int):
<xsd:attribute name="length" type="xsd:int" use="required"/>
@XmlAttribute(name = "length", required = true)
protected int length;
@XmlAttribute(name = "length")
protected Integer length;