JAXB返回null而不是空字符串 [英] JAXB return null instead empty string
问题描述
如果在解组时,如果XML属性值为空,我如何检索 null
值?现在我在getter中检查 null
:
How I can retrieve null
value, when unmarshalling, if inside XML attribute value is empty ? Now I make inside my getters checking for null
:
public String getLabel() {
if (label.isEmpty()) {
return null;
}
else {
return label;
}
}
但可能存在其他更优雅的方式吗?
But may be exist some other, more elegant way?
谢谢。
推荐答案
我认为您的XML看起来或多或少像这样:
I think your XML looks more or less like this:
<myElement></myElement>
不幸的是,这意味着您传递空字符串。
This, unfortunately, means, that you are passing an empty string.
如果你想传递 null
,你有两个选择:
If you want to pass null
you have two options:
- 根本不传递此标记(您的XML根本不应包含
< myElement />
标记)。 - 使用
xsi:nil
。
- Do not pass this tag at all (your XML should not contain
<myElement/>
tag at all). - Use
xsi:nil
.
如果使用 xsi:nil
,首先必须将xml元素(在XSD文件中)声明为 nilable
,就像这样:
If using xsi:nil
, first you have to declare your xml element (in XSD file) as nilable
, like this:
<xsd:element name="myElement" nillable="true"/>
然后,在里面传递 null
值XML执行此操作:
Then, to pass the null
value inside XML do this:
<myElement xsi:nil="true"/>
或者这个:
<myElement xsi:nil="true"></myElement>
这样,JAXB知道你要传递 null
而不是空字符串。
This way, JAXB knows, that you are passing null
instead of an empty String.
这篇关于JAXB返回null而不是空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!