Jump to: navigation, search

EclipseLink/UserGuide/MOXy/Simple Values/Enums

EclipseLink MOXy

Mailing ListForumsIRC
Help Wanted
Bug Day
Browse Source

Mapping Enums

Java enums can be mapped to XML using the @XmlEnum and @XmlEnumValue annotations.

Mapping Enums using Constant Names

The following schema demonstrates an XML enumeration:

<xs:simpleType name="CustomerType">
   <xs:restriction base="xs:string"/>
      <xs:enumeration value="PROMO_CUSTOMER"/>
      <xs:enumeration value="NEW_CUSTOMER"/>
      <xs:enumeration value="VIP"/>
      <xs:enumeration value="NORMAL"/>

If your enum constant names themselves are sufficient for the XML representation, you can simply use the @XmlEnum annotation:

public class Customer {
   private CustomerType type = CustomerType.NEW_CUSTOMER;
   private enum CustomerType { PROMO_CUSTOMER, NEW_CUSTOMER, VIP, NORMAL }

The following example shows how to define this mapping in EclipseLink OXM Metadata:

   <xml-enum java-enum="CustomerType" value="java.lang.String">
      <xml-enum-value java-enum-value="PROMO_CUSTOMER"/>
      <xml-enum-value java-enum-value="NEW_CUSTOMER"/>
      <xml-enum-value java-enum-value="VIP"/>
      <xml-enum-value java-enum-value="NORMAL"/>
   <java-type name="Customer">
      <xml-root-element name="customer"/>
         <xml-element java-attribute="type" type="CustomerType"/>

When marshalled to XML, a Customer would look like this:


Mapping Enums to Custom XML Values

Given the following XML schema enumeration:

<xs:simpleType name="RewardLevel">
   <xs:restriction base="xs:int">
      <xs:enumeration value="1"/>
      <xs:enumeration value="5"/>
      <xs:enumeration value="10"/>
      <xs:enumeration value="25"/>

The @XmlEnumValue annotation is used to provide an XML value for each enum constant:

public class Customer {
   private RewardLevel discount = RewardLevel.NONE;
   private enum RewardLevel { 
      @XmlEnumValue("0") NONE(0), 
      @XmlEnumValue("5") BRONZE(5), 
      @XmlEnumValue("10") SILVER(10),
      @XmlEnumValue("25") GOLD(25),
      @XmlEnumValue("40") PLATINUM(40);

When marshalled to XML, a Customer would look like this:


Version: 2.2.0 Draft
Other versions...