JAXB: Anonymous simple types as enums?

后端 未结 3 1282
感动是毒
感动是毒 2020-12-16 01:18

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:

    

        
相关标签:
3条回答
  • 2020-12-16 01:56

    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>
    

    0 讨论(0)
  • 2020-12-16 02:08

    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>
    
    0 讨论(0)
  • 2020-12-16 02:10

    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)

    0 讨论(0)
提交回复
热议问题