2010-07-15 67 views
3

JAXB解組xml數據時遇到問題。JAXB拋出錯誤解編空int,雙或日期屬性

JAXB在從xml解編int,doubledate屬性的空值時拋出異常。例如,它在解組以下xml數據時拋出java.lang.NumberFormatException

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

以下是我的架構:

<?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> 

對不起,凌亂的XML。我無法在輸入中輸入「左角」符號。誰能幫我嗎?

非常感謝。

+0

使用上面的代碼圖標格式化XML,它會更好看。 – duffymo 2010-07-15 01:01:06

+0

非常感謝。你使用了什麼代碼圖標? – David 2010-07-15 01:23:49

+0

使用0和1秒的按鈕(010101)等 – Dunderklumpen 2010-07-15 01:43:06

回答

2

錯誤被拋出,因爲空字符串「」不是有效的double。如果需要價格,則必須爲其分配有效的雙倍值。

而不是price =「」您應該設置一個值,如price =「0」或使該屬性爲可選。

有效的價格屬性:

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

價格屬性作爲可選屬性:

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

Dunderklumpen,感謝您的幫助。我不允許更改xml數據。但是,即使我將該屬性設置爲可選,我仍然有相同的異常。 startDate =「」或者minimumOrderQty =「」也會得到異常。你知道我能做的任何事情來強制JAXB接受空值作爲有效嗎?謝謝 – David 2010-07-15 01:16:52

+0

違反XSD時無法解析XML。您需要更改XSD定義以使price屬性爲String。 JAXB將它解析爲一個字符串屬性。然後,可以在JAXB解析之後進行字符串到數字的轉換,此時可以將有效數字從字符串轉換爲數字。 – Dunderklumpen 2010-07-15 01:41:40

+0

必須具體說明,您應該將屬性價格更改爲type =「xs:string」 – Dunderklumpen 2010-07-15 01:55:19

1

您可能會限制價格的屬性類型爲空字符串和整數值的聯合。雖然這仍然會將price屬性映射到XML Schema的String驗證,但會檢查只有空字符串和整數是否有效作爲price屬性的值。這裏的模式示例:

<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>