Search code examples
javaxmljakarta-eejaxbwsdl

How to forbid some enum value in enum type to XML representation mapping?


I use @XmlEnum and @XmlEnumValue for mapping enum to XML representation (WSDL file). I need to omit one of the enumeration values. So it won't be a part of the WSDL file.

I need to omit enum value NONE. Tried this but doesn't work.

@XmlEnum
public enum Title { 
   @XmlEnumValue("mrs") MRS,
   @XmlEnumValue("mrs") MR,
   NONE;
   ..
}

This is the generated WSDL file.

<xs:simpleType name="title">
  <xs:restriction base="xs:string">
    <xs:enumeration value="mrs"/>    
    <xs:enumeration value="mr"/>
    <xs:enumeration value="NONE"/> <!-- I need to get rid of this enum value -->
  </xs:restriction>
</xs:simpleType>

Solution

  • You should be able to use an XmlAdapter for this. Have it convert between your enum and an enum with the desired items.

    import javax.xml.bind.annotation.*;
    import javax.xml.bind.annotation.adapters.XmlAdapter;
    
    public class TitleAdapter extends XmlAdapter<TitleAdapter.AdaptedTitle, Title>{
    
        @XmlType(name="title")
        public enum AdaptedTitle {
            @XmlEnumValue("mrs") MRS,
            @XmlEnumValue("mrs") MR
        }
    
        @Override
        public Title unmarshal(AdaptedTitle v) throws Exception {
            switch(v) {
            case MRS:
                return Title.MRS;
            case MR:
                return Title.MR;
            }
            return null;
        }
    
        @Override
        public AdaptedTitle marshal(Title v) throws Exception {
            switch(v) {
            case MRS:
                return AdaptedTitle.MRS;
            case MR:
                return AdaptedTitle.MR;
            }
            return null;
        }
    
    }
    

    Then change your Title enum to:

    import javax.xml.bind.annotation.adapters.*;
    
    @XmlJavaTypeAdapter(TitleAdapter.class)
    public enum Title { 
       MRS,
       MR,
       NONE;
    }