开发者

How to enable schema validation so that JAXB rejects empty element?

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)

Here is how it appears in the XML instance:

(Please see my comments below)

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

Thanks


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>

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.

  • XML schema restriction pattern for not allowing empty strings

For an example see:

  • http://bdoughan.blogspot.com/2010/12/jaxb-and-marshalunmarshal-schema.html


you can use minOccurs parameter

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜