When generating Java from an XSD via the XJC compiler, I always get the type java.lang.String for elements with anonymous simpleTypes like this:
<xsd:element name="Product">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="Product1"/>
<xsd:enumeration value="Product2"/>
<xsd:enumeration value="Product3"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
Of course, I want an enumeration for this. Is there a way to trick XJC into generating and using one?
We are using JAXB 2.1.3. Note: before you ask, no, I cannot change the schema and adapt it to XJC's bugs.
You have to put into your XJC File:
<jxb:bindings node="//xsd:element[@name='Product']/xsd:simpleType">
<jxb:typesafeEnumClass name="ProductType" />
</jxb:bindings>
or
<jxb:bindings node="//xsd:element[@name='Produkt']">
<jxb:bindings node="./xsd:simpleType">
<jxb:typesafeEnumClass name="ProduktType" />
</jxb:bindings>
</jxb:bindings>
Here is an example of how I implemented this. I will add the whole xjb for completeness since I admit looking at existing examples I still found it a little confusing.
Here´s the .xjb file
<?xml version="1.0" encoding="UTF-8"?>
<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
jaxb:version="1.0">
<jaxb:bindings schemaLocation="search-constraints.xsd"
node="/xs:schema">
<jaxb:bindings node="//xs:simpleType[@name='booleanStringType']">
<jaxb:typesafeEnumClass name="BooleanStringType" />
</jaxb:bindings>
</jaxb:bindings>
</jaxb:bindings>
Here, the bindings refer to my simple types which are declared at root level in my search-constraints.xsd. Here is an extract of that file:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.com"
xmlns:tns="http://www.example.com"
elementFormDefault="qualified"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
jaxb:version="1.0">
...
<xs:simpleType name="booleanStringType">
<xs:restriction base="xs:string">
<xs:enumeration value="true" />
<xs:enumeration value="false" />
</xs:restriction>
</xs:simpleType>
I had a very similar question, I asked on the JAXB mailing list and got this fairly helpful response (haven't had time to try it out though)
edit: if you're talking about automatically generating the enum class, rather than just automatically mapping to an enum class you write yourself, I would think that you could write a java class that would parse the schema file and autogenerate the java code for that enumeration. (then run that java class whenever you call xjc)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With