2

I'm current working on a Java code that is using JaxB to handle reading/writing of xml information. It populates a Java class which is used throughout the program. At certain points, the class is marshalled and written back into xml. I'm not having problems with this, and things are functioning as expected.

What I am curious about is if there is a way to alter the format of how JaxB writes out floating point numbers. For instance, part of the xml schema I am using contains the following excerpt:

.
.
<xs:element name="myObfuscatedValue">
  <xs:complexType>
    <xs:simpleContent>
      <xs:extension base="xs:double">
        <xs:attrbute name="myObfuscatedValue__comment" type="comment" use="optional" />
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
</xs:element>
.
.

So when I unmarshall it, 'myObfuscatedValue' basically comes in as a Double. I then have a wrapper class around the JaxB generated classes that allows the user to access/modify the variables via standard setters/getters. Marshalling back works fine as well.

What I ALSO want to do is have JaxB write the double out in a specific number format (something similar to a DecimalFormat like "0.0000E00" . Is this possible to do easily? I have been bounced around to several different resources on how to do this, but I admit that my knowledge of xml/schemas/JaxB is not up to date. Is there a way to alter the xjc call to do this? If possible, I want to avoid changing the schema file if possible (it's used by multiple codes in different languages, and I'd have to understand if changing it would break any of those codes first).

Any help, insight or suggestions on this matter would be greatly appreciated.

K.Niemczyk
  • 1,130
  • 3
  • 12
  • 26

1 Answers1

1

You can use an XmlAdapter to customize how a value is represented in XML. Below is an example demonstrating how to use an XmlAdapter if you are generating an object model from an XmlSchema:

Here is another example using XmlAdapter when you start from Java classes:

Community
  • 1
  • 1
bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • 1
    Blaise. I am unable to make it into work today, but I will attempt your method tomorrow and post of my status after wards. Thank you for your response. – K.Niemczyk Oct 13 '11 at 10:33
  • Blaise, Thanks for the resource! Using your tutorial I was able to get things to behave as I wished. My only comment is that while I did end up using an external binding file as your example showed, I was unable to limit it to a specific element. However, I was able to create a global binding (which in the end works better for my purposes) that accomplished the same thing. When I tried to limit it to a specific element, such as in your example, I started receiving NullPointerExceptions from xjc. – K.Niemczyk Oct 14 '11 at 17:46