javaxmlxsdjaxbxml-binding

Add/Modify an element to XML file using JAXB marshal


I am using JAXB to generate java code from XML, which has an enum

    <xs:simpleType name="color">
    <xs:restriction base="xs:string">
        <xs:enumeration value="Blue"/>
        <xs:enumeration value="Green"/>
        <xs:enumeration value="Yellow"/>
    </xs:restriction>
</xs:simpleType>

I want to add couple more colors to this enum, say Red and White. we do not want to update xsd or generated XML/Java code because those are not owned by us and we want to maintain it as it is.

Option 1. If there is a way to read the XSD in a way that when it reads xs:simpleType name="color", I can add colors to the enum, so generated java enum has all needed values

Option 2. If I can write an adapter which can help me to add values in generated Enum

I have checked XMLAdapter but overriding that doesn't help in my case. Since its an enum, I find it hard to modify it as Enums are meant to be constant in Java


Solution

  • Since it was difficult to insert values in an enum, we converted "color" element to a String type from Enum using customized JAXB bindings.

    <jaxb:bindings node="//xs:simpleType[@name='color']">
      <jaxb:typesafeEnumClass map="false" />
    </jaxb:bindings>
    

    New values can now be inserted. We understand this is risky as now "color" element can accept any string, but it works for us from our project point of view.