Tag is not getting removed from XML even after returning null from XmlAdapter in JAXB

331 Views Asked by At
  1. 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>

  1. 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;
      }
    
    }
    
  2. 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;
    
  3. After above changes the XML generated like below:

<Employee> <FirstName>Amit</FirstName> </LastName> </Employee>

  1. 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.

1

There are 1 best solutions below

0
Niv Bromberg On

You may set the XML's LastName element definition with required=true.
This will cause the generated lastName property to be annotated with @XmlAttribute(required=true).
This way JAXB doesn't serialize the element if it's null.