title: JAXB marshalling: treat empty object like it's null
body: <p>I want to explain my issue with a simple example:</p>
  
  <p><strong>Foo:</strong></p>
  
  <pre><code>@SomeXMLAnnotations
  public class Foo {
      // Bar is just a random class with its own XML annotations
      @XmlElement(required = true)
      Bar someBarObj;
  
      boolean chosen = true;
      boolean required = true;
  
      public Foo(){ 
          chosen = false;
      }
  
      public Foo(Bar someBarObj){
          this.someBarObj = someBarObj;
      }
  }
  </code></pre>
  
  <p><strong>MyClass:</strong></p>
  
  <pre><code>@SomeXMLAnnotations
  public class MyClass {
  
      @XmlElement(required = false)
      Foo anyFooObj;
  
      @XmlElement(required = true)
      Foo anyFooObjRequired;
  
      public MyClass (){ }
  
      public MyClass (Foo anyFooObj, Foo anyFooObjRequired){
          this.anyFooObj = anyFooObj;
          if(anyFooObj == null)
              this.anyFooObj = new Foo();
          /*
           * This is the reason why i can't let 'anyFooObj' be 'null'.
           * So 'anyFooObj' MUST be initialized somehow.
           * It's needed for some internal logic, not JAXB.
           */
          anyFooObj.required = false;
  
          this.anyFooObjRequired = anyFooObjRequired;
      }
  }
  </code></pre>
  
  <p><strong>Example Objects:</strong></p>
  
  <pre><code>Foo fooRequired = new Foo(new Bar());
  MyClass myObj = new MyClass(null, fooRequired); 
  </code></pre>
  
  <p>When i try to marshal <code>myObj</code> now, it throws an exception like this:</p>
  
  <pre><code>org.eclipse.persistence.oxm.record.ValidatingMarshalRecord$MarshalSAXParseException; 
  cvc-complex-type.2.4.b: The content of element 'n0:anyFooObj ' is not complete.
  One of '{"AnyNamespace":someBarObj}' is expected.
  </code></pre>
  
  <p>This happens because <code>anyFooObj</code> is initialized but it's required, member 
  <code>someBarObj</code> isn't.</p>
  
  <p><strong>Possible Solution:</strong></p>
  
  <p>I know i could add this method to <code>MyClass</code>: </p>
  
  <pre><code>void beforeMarshal(Marshaller m){
      if(! anyFooObj.chosen)
          anyFooObj= null;
      }
  }
  </code></pre>
  
  <p>But I have a lot of classes and those classes have a lot of not required fields. 
  So this solution would take ages and doesn't look like a proper solution as well.</p>
  
  <p><strong>My Question:</strong></p>
  
  <p>Is there a way to tell JAXB that it should treat empty objects like they were <code>null</code>? Or that it should ignore an element when it's not properly set. Something like this for example:</p>
  
  <pre><code>@XmlElement(required = false, ingnoreWhenNotMarshallable = true)
  Foo anyFooObj;
  </code></pre>
  
  <p><strong>NOTE:</strong> </p>
  
  <p>I'm NOT the developer of the code. I just have to add JAXB to the project and make everything compatible with a given XSD file. I'm NOT allowed to change the relation between classes.</p>