2011-09-21 42 views
3

我有這兩個類:如何在編組爲xml時告訴jaxb截斷BigDecimal?

@XmlAccessorType(XmlAccessType.FIELD) 
public class OpportunityLocation 
{ 

    @XmlElement 
    private LatitudeLongitude coordinates; 
    [...] 
} 

public class LatitudeLongitude implements Serializable 
{ 
    private BigDecimal latitude; 
    private BigDecimal longitude; 
    [...] 
} 

OpportunityLocation序列化,我得到

<location> 
    [...] 
    <coordinates> 
    <latitude>51.53684899999999657893567928113043308258056640625</latitude> 
    <longitude>-0.1325880000000000114024345521102077327668666839599609375</longitude> 
    </coordinates> 

現在,我一直要求提供的XSD驗證XML,我設置的類型latitudelongitude爲xsd:小數,但驗證抱怨

Element 'latitude': '51.53684899999999657893567928113043308258056640625' is not a valid value of the atomic type 'xs:decimal'. 

(同一經度)

描述座標的XSD片段

<xs:complexType name="latitudeLongitude"> 
    <xs:all> 
     <xs:element name="latitude" type="xs:decimal"/> 
     <xs:element name="longitude" type="xs:decimal"/> 
    </xs:all> 
</xs:complexType> 

我認爲最好的解決辦法是截斷經/緯度值,因爲沒有點有那麼多精密擺在首位。

我該如何指導JAXB來做到這一點?

回答

0

或者乾脆使用性BigDecimal.setScale()。如果適用於您的情況,則無需使用XmlAdapter。

BigDecimal bd = new BigDecimal((double) 1.2345); 
bd = bd.setScale(2, RoundingMode.HALF_UP);