Make JAXB XJC generate a wrapping class for a simple type

Adrian Mitev picture Adrian Mitev · Oct 4, 2012 · Viewed 8.4k times · Source

I have the following xml types:

<xsd:element name="FaxNumbers" minOccurs="0">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="FaxNumber" type="FaxNumber" maxOccurs="unbounded" />
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>

The FaxNumber type looks like this:

<xsd:simpleType name="FaxNumber">
    <xsd:restriction base="xsd:string">
        <xsd:minLength value="1" />
    </xsd:restriction>
</xsd:simpleType>

The resulting xml should be something like this:

<FaxNumbers>
    <FaxNumber>3878374</FaxNumber>
    <FaxNumber>387833434</FaxNumber>
    <FaxNumber>3878334</FaxNumber>
</FaxNumbers>

When running JAXB XJC to generate java classes from XSD it generates the following class:

@XmlType(name = "FaxNumbers")
public class FaxNumbers  {

    /**
     * No comment.
     */
    @XmlElement(name = "FaxNumber", required = true)
    protected List<String> faxNumber = new ArrayList<String>();

}

However i would like bind FaxNumber to composite class like this:

@XmlType(name = "FaxNumbers")
public class FaxNumbers  {

    /**
     * No comment.
     */
    @XmlElement(name = "FaxNumber", required = true)
    protected List<FaxNumber> faxNumber = new ArrayList<String>();

}

Where FaxNumber class looks like this:

public class FaxNumber{

    @XmlValue
    private String value;
}

Is there a way to define such binding in JAXB bindings xml?

Note: Unfortunately I don't have control over and cannot change the XSD

Answer

Ian Roberts picture Ian Roberts · Oct 4, 2012

I don't think you can get xjc to generate such a FaxNumber class for you, but you can write it yourself and then use an external binding file to slot it in at the right place.

package com.example;
public class FaxNumber {
  private String value;
  // getter/setter

  public static FaxNumber parse(String s) {
    FaxNumber n = new FaxNumber();
    n.value = s;
    return n;
  }

  public static String print(FaxNumber n) {
    return n.value;
  }
}

Bindings:

<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
           xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
           jaxb:version="2.0">
  <jaxb:bindings schemaLocation="example.xsd">
    <jaxb:bindings node="//xsd:simpleType[@name='FaxNumber']">
      <jaxb:javaType name="com.example.FaxNumber"
          parseMethod="com.example.FaxNumber.parse"
          printMethod="com.example.FaxNumber.print"/>
    </jaxb:bindings>
  </jaxb:bindings>
<jaxb:bindings>