如何启用架构验证,以便JAXB拒绝空元素? [英] How to enable schema validation so that JAXB rejects empty element?

查看:45
本文介绍了如何启用架构验证,以便JAXB拒绝空元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个比较麻烦的JAXB解析问题.我正在使用JAXB RI2.x.我已经使用"unmarshaller.setSchema(schema)"启用了模式验证.但是,如果XML包含一个空元素,则JAXB不会引发任何验证错误.所以客户很高兴地传递空字符串值!

I have encountered a wiered JAXB parsing issue. I am using JAXB RI 2.x. I have enabled the schema validation using "unmarshaller.setSchema(schema)". However, if the XML contains an empty element, JAXB does not throw any validation error. So the clients are happily passing empty string values!!

以下是在架构中声明元素的方式:

Here is how the element is declared in the schema:

(请在下面查看我的评论)

(Please see my comments below)

这是它在XML实例中的显示方式:

Here is how it appears in the XML instance:

(请在下面查看我的评论)

(Please see my comments below)

即使它是必填字段,也已由JAXB成功验证.如何启用对这些空元素的拒绝?

Even though it is a required field, it is successfully validated by JAXB. How do I enable the rejection of such empty elements?

谢谢

推荐答案

您需要在XML模式中声明一个新的简单类型,该类型是对xsd:string的限制,其中包括minLength构面.

You need to declare a new simple type in your XML schema that is a restriction of xsd:string that includes the minLength facet.

<xs:element name="ChargeCode" type="stringMinSize1"/>
<xs:simpleType name="stringMinSize1">
    <xs:restriction base="xs:string">
        <xs:minLength value="1"/>
    </xs:restriction>
</xs:simpleType>

您还可以使用其他方面,例如pattern来进一步控制字符串内容的外观.一个典型的例子是加拿大邮递区号,在字母之间交替显示:

You can also use other facets such as pattern to further control what the string content looks like. A typical example is that of a Canadian postal code which alternates between letters:

<xs:element name="PostalCode" type="postalCode"/>
<xs:simpleType name="postalCode">
    <xs:restriction base="xs:string">
        <xs:pattern value="[A-Z]{1}[0-9]{1}[A-Z]{1} [0-9]{1}[A-Z]{1}[0-9]{1}"/>
    </xs:restriction>
</xs:simpleType>

下面的问题涉及一种模式,要求带内容的字符串.

The question below deals with a pattern to require strings with content.

有关示例,请参见:

这篇关于如何启用架构验证,以便JAXB拒绝空元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆