4

I am using Jaxb to parse xml. In the xml file I have list of items defined as follows:

<item>
   <currency_name>US Dollar</currency_code>
   <currency_code>USD</currency_code>
   <rate>3,0223</rate>
</item>

When I put in my xsd file the following line:

<xsd:element name="rate" type="xsd:string" minOccurs="1" maxOccurs="1"/>

I get 3,0223 as a string value, however when I put:

<xsd:element name="rate" type="xsd:double/BigDecimal/float" minOccurs="1" maxOccurs="1"/>

then I recieve 0.0/null. I think that the problem is in the "," separator. How to unmarshall rate value to BigDecimal?

BlueLettuce16
  • 2,013
  • 4
  • 20
  • 31

1 Answers1

1

If you are generating your model from XML Schema, below is an approach you can use to cause an XmlAdapter to be generated for your use case.

Formatter Object

You will need to create a class with methods that can convert the string to/from BigDecimal.

public class BigDecimalFormatter {

    public static String printBigDecimal(BigDecimal value) {
        // TODO - Conversion logic
    }

    public static BigDecimal parseBigDecimal(String value) {
        // TODO - Conversion logic
    }

}

External Bindings Document (bindings.xml)

An external binding document is used to specify that your custom conversion class should be used when converting the XML string to/from your BigDecimal property.

<jxb:bindings xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:jxb="http://java.sun.com/xml/ns/jaxb" version="2.1">
    <jxb:bindings schemaLocation="schema.xsd">
        <jxb:bindings node="//xs:element[@name='rate']">
            <jxb:property>
                <jxb:baseType>
                    <jxb:javaType name="java.math.BigDecimal"
                        parseMethod="forum20711223.BigDecimalFormatter.parseBigDecimal" printMethod="forum20711223.BigDecimalFormatter.printBigDecimal" />
                </jxb:baseType>
            </jxb:property>
        </jxb:bindings>
    </jxb:bindings>
</jxb:bindings>

XJC Call

The -b flag is used to reference the external binding document.

xjc -b binding.xml schema.xsd

Full Example

Community
  • 1
  • 1
bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • Thank you for your solution. You saved my day! ;) However I think that there should be java.math.BigDecimal instead of BigInteger, but that's only a small detail. – BlueLettuce16 Dec 20 '13 at 21:16
  • @Adam - I'm happy I could help. I have fixed that one `BigInteger`. – bdoughan Dec 20 '13 at 21:30
  • Is there a way to do it only with code in java? In my case, the classes generated from the schema are given by an external source. – PhoneixS Sep 11 '20 at 07:26