Print empty items

I have an object with two fields "name" and "address". JAXB ignores empty elements when converting an object to XMl.

For example: if I have name = "xyz" and address = null, then the output will be

<name>xyz</name> 

but what i want as output is how

 <name>xyz</name> <address></address> 

I saw the @XmlElement(nillable="true") option, but this gives the result as

 <name>xyz</name> <address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/> 

Please help me get the desired result.

Thanks in advance.

+4
source share
3 answers

A JAXB (JSR-222) will return an empty String "" as an empty element. You can set the address property for this to get the desired effect.


UPDATE # 1

I updated my question. Basically, the address element is NULL. Is this decision applicable to this?

You can use Marshal Event Callbacks to configure the address value.

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

UPDATE # 2

The only problem is that if I have 10 fields in the class, I will have to write if for all fields. Is there any other solution?

If you are using EclipseLink MOXy as a JAXB provider (I am the lead MOXy), then you can use the XmlAdapter for this use case.

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

package info

Then, if you specify it at the package level, it will apply to all displayed fields / properties of type String inside this package.

 @XmlJavaTypeAdapter(value=StringAdapter.class, type=String.class) package forum14691333; import javax.xml.bind.annotation.adapters.*; 

Additional Information

+5
source

If you use EclipseLink MOXy as a JAXB provider, you can use

 @XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE) @XmlElement(name = "address", nillable = true) private String address; 

Using this method, you do not need to write an adapter for all fields

+1
source

Just set an empty default value in the field.

 @XmlElement(required="true") private String address = ""; 

and you will get

 <address></address> 
0
source

All Articles