2
這是我的問題:我需要通過對象的名稱標籤來存在於XML中,但不具有nillable屬性:總之就像<name/>
。這是對象的代碼。 如果名稱爲空,我確實得到標籤<name xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
,但其他屬性可能會給客戶端帶來問題。JAXB - 防止nillable屬性xmlns:xsi =「http://www.w3.org/2001/XMLSchema-instance」xsi:nil =「true」
正如我已經閱讀,從語義上來說,這樣做代表空值是有意義的(使用@XmlElement(nillable=true)
)。
package com.mns.mnsutilities.jaxb.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name="Emp_MNS")
@XmlType(propOrder= {"name", "age", "role", "gender", "addressesList"})
public class Employee {
private int id;
private String gender;
private int age;
private String name;
private String role;
private String password;
private List<Address> addressesList;
public Employee() {}
public Employee(int id, String gender, int age, String name, String role,
String password) {
super();
this.id = id;
this.gender = gender;
this.age = age;
this.name = name;
this.role = role;
this.password = password;
}
public Employee(int id, String gender, int age, String name, String role,
String password, List<Address> addressesList) {
super();
this.id = id;
this.gender = gender;
this.age = age;
this.name = name;
this.role = role;
this.password = password;
this.addressesList = addressesList;
}
@XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@XmlElement(name = "gen", nillable=true)
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@XmlElement(nillable=true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@XmlTransient
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@XmlElementWrapper(name="addresses")
@XmlElement(name = "address")
public List<Address> getAddressesList() {
if(addressesList == null){
addressesList = new ArrayList<>();
}
return addressesList;
}
public void setAddressesList(List<Address> addressesList) {
this.addressesList = addressesList;
}
@Override
public String toString() {
return "Employee [id=" + id + ", gender=" + gender + ", age=" + age
+ ", name=" + name + ", role=" + role + ", password="
+ password + ", addressesList=" + addressesList + "]";
}
}
記住'' 是一樣' ' - 如果你設置的值到_empty string_,這是從'null'不同,你會得到你想要的輸出。 –
以下是對@IanRoberts發表的評論的迴應 - http://stackoverflow.com/a/23086346/383861 –