| Author |
Is there a way to construct empty xml elements while marshalling a jaxb object
|
Nevin kumar
Ranch Hand
Joined: Mar 15, 2008
Posts: 93
|
|
Dear Ranchers,
while marshalling If we don't initialize a few jaxb object properties it will not show those properties in the marshalled String(StringWriter ) but in my case I need to show all the elements irrespective of whether there are initialized or not.If it is a String there is no problem I'm initializing to empty ,but the problem is when I had datatypes like int,boolean and date also.In this case if I need to show the elements I need to show the elements with default values such 0,false which is not proper to show like that.
example:
Imagine employee object has properties like name,age etc
what it returns is(ignoring age as I didn't initialize)
but I'm expecting in either this form
or this form
If I initialize age(datatype is primitive int ) to default value in java code, it will return like this which doesn't make sense,age as 0.
Is there any to to show empty elements when uninitialized.Any help highly appreciated, I'm really struggling with this ,
|
 |
William Brogden
Author and all-around good cowpoke
Rancher
Joined: Mar 22, 2000
Posts: 12269
|
|
If this was my problem I would drop JAXB serialization and construct the XML "by hand" using println statements to a java.io.CharArrayWriter
It really is pretty simple and the end result will look exactly like what you want.
Bill
|
Java Resources at www.wbrogden.com
|
 |
Naren Chivukula
Ranch Hand
Joined: Feb 03, 2004
Posts: 542
|
|
Hi Nevin,
As we know Java assigns default values to instance variables, I'm surprised why the default integer value 0 not being picked up by JAXB(I presume you use this for data binding and for that matter that doesn't really matter) and accordingly create xml message. Why don't you use minOccurs=1 in your schema before generating binding objects?
|
Cheers,
Naren (SCJP, SCDJWS and SCWCD)
|
 |
Ivan Krizsan
Bartender
Joined: Oct 04, 2006
Posts: 2193
|
|
Hi!
For some fields, JAXB generates not only the field, an integer in this case, but also a flag that indicates whether the field has been set or not.
I suspect that this is what happens in this case - the default value indicates that the field has not been set and it will not become marshalled.
Take a look at the generated JAXB classes to be sure.
I also suspect that if the type of the field is a Java primitive, such as int or long, then you will always have the flag indicating whether the field has been set or not, regardless of whether you set minOccurs to 1 or 0. The best way to know is to try!
Best wishes!
|
My free books and tutorials: http://www.slideshare.net/krizsan
|
 |
 |
|
|
subject: Is there a way to construct empty xml elements while marshalling a jaxb object
|
|
|