I have an empty tag like this <tagName/>
. When I unmarshalling it if this property is the type of long or float it is null. But if this property is the type of string, the property is tagName = '';
. And after marshalling is <tagName></tagName>
. How can I set empty tag name which is string java property to null while unmarshalling?
There are (at least) 2 ways to do this.
For example a class Cart:
@XmlRootElement(name = "Cart")
@XmlAccessorType(XmlAccessType.FIELD)
public class Cart {
@XmlJavaTypeAdapter(EmptyTagAdapter.class)
protected String tagName;
}
can use an adapter like below:
public class EmptyTagAdapter extends XmlAdapter<String, String> {
@Override
public String marshal(String arg0) throws Exception {
return arg0;
}
@Override
public String unmarshal(String arg0) throws Exception {
if(arg0.isEmpty()) {
return null;
}
return arg0;
}
}
For an xml that looks like this:
<Cart>
<tagName/>
</Cart>
You would get the empty tagName as null.
For example as below:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.1">
<xs:element name="Cart">
<xs:complexType>
<xs:all>
<xs:element name="tagName" type="xs:string" nillable="true" />
</xs:all>
</xs:complexType>
</xs:element>
</xs:schema>
and then you would need to have in your xml with the empty element xsi:nil="true" as this example:
<Cart xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<tagName/>
<tagName xsi:nil="true" />
</Cart>
It would have the same result, the value as null.
The use of the adapter is more to my liking but depends on your case. Hopefully one of the cases covers you.