我有一个带有两个字段“名称”和“地址”的对象。 JAXB 在将对象转换为 XML 时忽略空元素。
例如:如果我有 name="xyz"和 address=null 那么 out 将是
<name>xyz</name>
但我想要作为输出
<name>xyz</name>
<address></address>
我已经看到选项
@XmlElement(nillable="true")
但这使输出为<name>xyz</name>
<address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
请帮助我获得所需的输出。
提前致谢。
最佳答案
JAXB (JSR-222)实现将输出一个空字符串 ""
作为空元素的值。您可以设置 address
属性来获得想要的效果。
更新 #1
I have updated my question. Basically the address element is NULL. Is this solution applicable to that as well?
您可以利用 Marshal Event Callbacks调整
address
的值.import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
private String name;
private String address;
private void beforeMarshal(Marshaller marshaller) {
if(null == address) {
address = "";
}
}
private void afterMarshal(Marshaller marshaller) {
if("".equals(address)) {
address = null;
}
}
}
更新 #2
The only concern is that if I have 10 fields in the class I will have to write if for all the fields. Is there any other solution?
如果您使用 EclipseLink MOXy作为您的 JAXB 提供商(我是 MOXy 负责人),那么您可以使用
XmlAdapter
对于这个用例。XmlAdapter (StringAdapter)
package forum14691333;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class StringAdapter extends XmlAdapter<String, String> {
@Override
public String marshal(String string) throws Exception {
if(null == string) {
return "";
}
return string;
}
@Override
public String unmarshal(String string) throws Exception {
if("".equals(string)) {
return null;
}
return string;
}
}
包裹信息
然后,如果您在包级别指定它,它将适用于类型
String
的所有映射字段/属性。在那个包裹内。@XmlJavaTypeAdapter(value=StringAdapter.class, type=String.class)
package forum14691333;
import javax.xml.bind.annotation.adapters.*;
更多信息
关于jaxb - 输出空元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14691333/