在解组JAXB注释类时需要一个空XML

时间:2010-04-22 10:45:08

标签: java jaxb

我有一个JAXB注释类Customer,如下所示

@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;
}
}

我需要向用户返回一个表示此的空XML,以便他可以填充XML中的必要值并发送请求 所以我需要的是:

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

如果我只是创建一个空对象

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

我得到的是toplevel元素,因为该类的其他字段未设置。

如何获得这样一个空XML?我尝试将nillable = true注释添加到元素中,然而,这会返回一个带有xsi:nil =“true”的XML,然后导致 我的unmarshaller忽略了这一点。

我如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

<Name></Name>这样的东西代表一个空的非空字符串,但是你的java对象将用nulls初始化。如果希望JAXB编组空值,则需要设置这些值:

Customer cust = new Customer() ;
cust.setName("");
cust.setAddress("");
marshaller.marshall(cust, sw);
相关问题