Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JaxB generation, How do I get a bigDecimal from my xsd?

I have an xsd annotation that I am trying to get to Marshal into a java object. I would like the java to end up with BigDecimal for its value. What do I enter in the xsd to make it do this? I am using an xjc ant task

<xjc schema="my.xsd" destdir="generated" header="false" extension="true" />

Here is the relevant xsd -

<complexType name="Size">
    <attribute name="height" type="BigDecimal"></attribute> <!-- this is wrong-->
</complexType>

I would like to end up with this for the generated class -

public class Size { 
@XmlAttribute(name = "height")
    protected BigDecimal height;
}
like image 816
spartikus Avatar asked Jul 23 '13 23:07

spartikus


2 Answers

A JAXB (JSR-222) implementation will generate a java.math.BigDecimal from the decimal type (see Table 6-1 in the JAXB 2.2 specification).

XML Schema (schema.xsd)

<?xml version="1.0" encoding="UTF-8"?>
<schema 
    xmlns="http://www.w3.org/2001/XMLSchema" 
    targetNamespace="http://www.example.org/schema" 
    xmlns:tns="http://www.example.org/schema" 
    elementFormDefault="qualified">

    <element name="foo">
        <complexType>
            <sequence>
                <element name="bar" type="decimal"/>
            </sequence>
        </complexType>
    </element>

</schema>

XJC Call

xjc schema.xsd

Java Model (Foo)

package org.example.schema;

import java.math.BigDecimal;
import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {"bar"})
@XmlRootElement(name = "foo")
public class Foo {

    @XmlElement(required = true)
    protected BigDecimal bar;

    ...

}
like image 81
bdoughan Avatar answered Nov 09 '22 12:11

bdoughan


I figured this out. The answer is to use a binding.xjb class

binding =

<jxb:javaType 
     name="java.math.BigDecimal" 
     xmlType="xs:decimal"/>

ant -

<xjc schema="my.xsd" destdir="generated" binding="myBinding.xjb" header="false" extension="true" />

xsd =

<attribute name="height" type="decimal"></attribute>

This means anything marked as type decimal will turn into a big decimal but in my case that is ok. Hope this helps someone else.

like image 27
spartikus Avatar answered Nov 09 '22 11:11

spartikus