tags:

views:

54

answers:

2

I have a JAXB annotated class Customer as follows

@XmlRootElement(namespace = "http://www.abc.com/customer")
public class Customer{

private String name;
private Address address;


@XmlTransient
private HashSet set = new HashSet<String>();

public String getName(){
return name;
}

@XmlElement(name = "Name", namespace = "http://www.abc.com/customer" )
public void setName(String name){
this.name = name;
set.add("name");
}

public String getAddress(){
return address;
}

@XmlElement(name = "Address", namespace = "http://www.abc.com/customer")
public void setAddress(Address address){
this.address = address;
set.add("address");
}

public HashSet getSet(){
return set;
}
}

I need to return an empty XML representing this to the user, so that he may fill the necesary values in the XML and send a request So what I require is :

<Customer>
<Name></Name>
<Address></Address>
</Customer>

If i simply create an empty object

Customer cust = new Customer() ;
marshaller.marshall(cust,sw);

all I get is the toplevel element since the other fields of the class are unset.

What can I do to get such an empty XML? I tried adding the nillable=true annotation to the elements however, this returns me an XML with the xsi:nil="true" which then causes my unmarshaller to ignore this.

How do I achieve this?

A: 

Something like <Name></Name> represents an empty, non-null String, but your java object is going to be initialized with nulls. If you want JAXB to marshall empty values, you need to set those values:

Customer cust = new Customer() ;
cust.setName("");
cust.setAddress("");
marshaller.marshall(cust, sw);
skaffman
My class could have members of any data type. If its an integer I will have to initialize to 0, boolean to false etc. I am writing a generic program which should give me a blank for all elements irrespective of the data type, and also initialize the complex types and their elements with a blank value. which means I will have to recursively loop through all the elements and their child elements.
sswdeveloper
@sswdeveloper: That's true. However, that's the way it works. `<Name></Name>` in XML means a different thing to having no element present. If you want the element present, you have to supply a value.
skaffman
A: 

you can supply defaults to variables, in your case:

private String name = "";
private Address address = new Address();

All the primitive value will already have their defaults.

ekeren
But then the primitive integer fields will be marshalled as `<foo>0</foo>`, rather than `<foo></foo>`
skaffman
@skaffman right, I didn't think about it
ekeren