XSD - 允许元素类型为整数或空
我需要能够将简单元素类型设置为整数,但允许它也为空。如果该示例为空并且空白字段不是整数,则此示例会发送错误。我该如何解决这个问题?
<xsd:element name="weight" type="xsd:integer"/>
I need to be able to set a simple element type as an integer but allow it to also be empty. This example sends an error if its empty and a blank field is not an integer. How can I get round this?
<xsd:element name="weight" type="xsd:integer"/>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您所要做的就是对同一元素分配限制并对其进行联合,如下例所示:
通过使用此限制,您可以告诉 xml 验证允许任何整数值,并允许该元素为空。
What you have to do is assign restrictions on the same element plus make a union on them such as the following example:
By using this restriction, you tell the xml validation to allow any integer value and allowing the element if it is empty.
我们可以通过在 SimpleType 中
添加 NullOrInteger 作为您想要限制整数或空值的类型来实现此目的。
例如:
We can achieve this by making a SimpleType
Add NullOrInteger as the type where you want restriction for an integer or null value.
for example:
您需要将“nillable”属性设置为 true:
请参阅 XML Schema Primer。
You need to set the "nillable" attribute as true:
See the XML Schema Primer.
尝试上面的方法,应该可以工作;您很可能忘记添加 xsi:nil 属性。另外,请确保权重元素没有作为子元素的字符(空格仍然是不可接受的)。如果您确实必须传递一些字符而不是整数,则必须定义一个联合类型以允许两者。
Try the above, should work; most likely you forgot to add the xsi:nil attribute. Also, make sure that the weight element has no character as children (a white space would still not be acceptable). If you do have to pass some characters instead of an integer, than you have to define a union type to allow for both.
我通过搜索如何使用 xsd 模式使属性成为可为空整数并基于生成的 JAXB 类得出了这个答案。我在这里没有找到答案,所以在找到答案后,我决定分享它。以下 xsd 部分将生成不可为 null 类型的 int (int):
在 Java 代码中,这将导致:
如果我们放弃使用 required,我们将得到:
希望这对某人有帮助。即使这个答案可能与实际问题无关,我发现对于那些通过进行与我相同的搜索来到达这里的人来说,这里很有用!
I came up to this answer by searching how to get an attribute to be a nullable Integer, using xsd schema, and based on which JAXB classes are generated. I found no answer here, so after I discovered the answer, I decided to share it. The following xsd portion will generate a not nullable type of int (int):
In Java code this will result:
If we drop the use required, we will get:
Hope this helps someone. And even if this answer might not be related to the actual question, I find it useful to be here for those who will get here by doing the same search I did!