开发者

JAXB throws Error when unmarshalling empty int, double or date attributes

开发者 https://www.devze.com 2023-01-07 13:55 出处:网络
I met a problem when JAXB unmarshalling xml data. JAXB throws exception when unmarshalling empty value for int, double or date attribute from xml. For example, it throws java.lang.NumberFormatExcepti

I met a problem when JAXB unmarshalling xml data.

JAXB throws exception when unmarshalling empty value for int, double or date attribute from xml. For example, it throws java.lang.NumberFormatException when it unmarshals the following xml data.

<sku displayName="iphone" price=""/>

The following is my schema:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="sku" type="SkuType" maxOccurs="unbounded"/>
    <xs:complexType name="SkuType">
        <xs:attribute name="displayName" type="xs:string" use="required"/>
        <xs:attribute name="price" type="xs:double" use="required"/>
        <xs:attribute name=开发者_运维百科"startDate" type="xs:dateTime" use="optional"/>
        <xs:attribute name="minimumOrderQty" type="xs:integer" use="optional"/>
    </xs:complexType>
</xs:schema>

Sorry for the messy xml. I can't type "left angle" sign in input. Can anyone help me out?

Thanks a lot.


The error is being thrown because the empty string "" is not a valid double. If price is required then it must be assigned a valid double value.

Instead of price="" you should either set a value like price="0" or make the attribute optional.

Valid price attribute:

<sku displayName="iphone" price="0"/>

Price attribute as an optional attribute:

<xs:attribute name="price" type="xs:double" use="optional"/>


You may restrict price attribute type to be union of empty string and integer values. While this will still map price attribute to String validation of XML Schema will check that only empty string and integers are valid as values for price attribute. Here's schema example:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <xsd:element name="product" type="product"/>

   <xsd:complexType name="product">
      <xsd:attribute name="name" type="xsd:string"/>
      <xsd:attribute name="price" type="emptyInt"/>
   </xsd:complexType>

   <xsd:simpleType name="emptyInt">
      <xsd:union>
         <xsd:simpleType>
            <xsd:restriction base="xsd:integer"/>
         </xsd:simpleType>
         <xsd:simpleType>
            <xsd:restriction base="xsd:token">
               <xsd:enumeration value=""/>
            </xsd:restriction>
         </xsd:simpleType>
      </xsd:union>
   </xsd:simpleType>
</xsd:schema>
0

精彩评论

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

关注公众号