Reputation: 12044
We have JAXB objects marshing/unmarshalling XML. Currently, we get this tag, even though everything inside it is empty. We need to completely get rid of the Top section if all its sub-elements are empty. (If at least one is not empty, it should exist.)
<ns2:Top>
<ns2:OrganizationName></ns2:OrganizationName>
<ns2:Address>
<ns2:Street1></ns2:Street1>
<ns2:Street2></ns2:Street2>
<ns2:City></ns2:City>
<ns2:ZipPostalCode></ns2:ZipPostalCode>
</ns2:Address>
</ns2:Top>
The JAXB class is defined as:
@XmlElement(name = "Top")
protected Top top;
Upvotes: 0
Views: 756
Reputation: 31300
You can control the amount of elements appearing in the marshalled XML by setting or not setting fields.
Root root = new Root();
root.setTop( new Top() ); // (1)
root.getTop().setAddress( new Address() ); // (2)
With lines (1) and (2), marshalling produces
<root><top><address/></top></root>
With just line (1), the XML will be
<root><top/></root>
Omitting both lines yields
<root/>
Once you have organizationName or address or both set in Top with some or all String fields set to the empty string (i.e., "") you'll have to write some code for pruning the useless fields. (Although it is highly questionable to set fields to the empty string if there isn't a useful value to be used.)
Later An adapter is a good idea. Annotate the element you want to keep, Top, or the one above it:
@XmlElement
@XmlJavaTypeAdapter(Adapter.class)
protected Top top;
And write an adapter to investigate the object hierarchy, replacing it with an empty top level element:
public class Adapter extends XmlAdapter { public Top unmarshal( Top v ) throws Exception { return v; } private boolean allEmpty( String... strings ){ for( String s: strings ){ if( s != null && ! s.equals( "" ) ) return false; } return true; } public Top marshal( Top top ) throws Exception { Address a = top.getAddress(); return allEmpty( top.getOrganizationName(), a.getStreet1(), a.getStreet1(), a.getCity(), a.getPostalCode(), a.getState(), a.getCountry() ) ? new Top() : top; } }
I have chosen Top, so you keep an empty <top>
, but you can do this one level higher.
Upvotes: 1