- I want to remove the empty tag from XML.
<Employee> <FirstName>Amit</FirstName> <LastName></LastName> </Employee>
So, in above XML lastName is coming as blank, and currently represented with Empty tags in XML. But I want the XML in below format:
<Employee> <FirstName>Amit</FirstName> </Employee>
So, extended the XmlAdapter like below:
package com.jaxb.domain; import javax.xml.bind.annotation.adapters.XmlAdapter; import org.springframework.util.StringUtils; public class NullifyAdapter extends XmlAdapter<String, String> { @Override public String unmarshal(String strValue) throws Exception { // TODO Auto-generated method stub return strValue; } @Override public String marshal(String strValue) throws Exception { if (StringUtils.isEmpty(strValue)) { return null; } return strValue; } }Register it a package level in the package-info.java like below:
@XmlJavaTypeAdapters({ @XmlJavaTypeAdapter(value=NullifyAdapter.class, type=String.class) }) package com.jaxb.domain; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters;After above changes the XML generated like below:
<Employee> <FirstName>Amit</FirstName> </LastName> </Employee>
In my jaxb binding class the field is defined as:
@XmlElement(name = "LastName") protected String lastName;
Please suggest, how to remove lastName completely? There are lot of fields which I need to remove so want a solution on similar lines.
You may set the XML's
LastNameelement definition withrequired=true.This will cause the generated
lastNameproperty to be annotated with@XmlAttribute(required=true).This way JAXB doesn't serialize the element if it's null.