Prevent JAXB from marshalling empty content for type with length restriction

20 Views Asked by At

I'm using CXF 4.0 with JAXB as data binding to generate webservices with a top-down approach.

The WSDL is given to me, which means I cannot change it.

I'm currently struggling to properly marshall some of the types defined in the schema.

Let's say I have the following types:

 <xs:complexType name="Foo">
    <xs:sequence>
      <xs:element name="bar" type="tns:Bar" minOccurs="0"/>
    </xs:sequence>
 </xs:complexType>

  <xs:simpleType name="Bar">
    <xs:restriction base="xs:string">
      <xs:minLength value="1"/>
      <xs:maxLength value="50"/>
    </xs:restriction>
  </xs:simpleType>

So the bar element is optional, but if it's there it must be at least 1 character long.

When the cxf-codegen-plugin generates Java classes from the XML schema, it maps the bar element to a String in the enclosing Fooclass:

public class Foo {

  protected String bar;

  public String getBar() {
      return bar;
  }

  public void setBar(String value) {
      this.bar = value;
  }
}

Now if bar is assigned an empty string, its marshalling is going to throw an error (cvc-minLength-valid).

I tried using an adapter to replace empty strings with null but it doesn't help: JAXB checks the unadapted value of the element to decide if it must write the associated tag.

I wrote an XJC plugin and managed to enforce type restrictions in the generated setters. It seems like overkill but I can't think of any other way to cope with this problem.

Can JAXB be configured to avoid marshalling empty content in this situation?

0

There are 0 best solutions below