title: How to prevent JAXB from writing unused namespaces during marshalling
body: <p>Has someone ever been able to remove unused namespaces during marshal of an object using JAXB? Here is a link of the requested feature: <a href="https://github.com/javaee/jaxb-v2/issues/103" rel="noreferrer">https://github.com/javaee/jaxb-v2/issues/103</a> (see description)</p>
  
  <p>Is there a property for configuring JAXB for this?
  Has this been fixed in MOXy? </p>
  
  <p>I am currently traversing the object that needs to be marshalled and extract all classes that need to be bound into <code>Class[] classesToBeBound</code>.
  Then I create a new <code>JAXBContext.newInstance(classesToBeBound)</code></p>
  
  <p>The unused namespaces now are not included in the XML.</p>
  
  <p>I know that xml validation is valid even with the unused namespaces but to me this is something a framework should handle.</p>
  
  <p>The following link <a href="https://blogs.oracle.com/enterprisetechtips/entry/customizing_jaxb" rel="noreferrer">https://blogs.oracle.com/enterprisetechtips/entry/customizing_jaxb</a> mentions various fixed (see middle of the text somewhere) but when trying to find the solution in those links either the link is broken or no-one really solved it.</p>
  
  <p>Any comments are welcome.</p>
  
  <p>(EDIT)
  Plain text:</p>
  
  <p>GIVEN </p>
  
  <pre><code>a new instance of JAXBContext and add 2 classes with each a separate namespace. 
  </code></pre>
  
  <p>WHEN </p>
  
  <pre><code>marshalling a class that has these 2 classes as a property but only 1 of them is not null 
  </code></pre>
  
  <p>THEN </p>
  
  <pre><code>I expect only the namespace of the property that is not null to be visible in the XML. 
  </code></pre>
  
  <p>BUT the ACTUAL is </p>
  
  <pre><code>that both namespaces are in the xml. 
  </code></pre>
  
  <p>So my question was how can I remove or tell JAXB to NOT write the unused namespaces?</p>
  
  <p>To put it in java-code:
  GIVEN </p>
  
  <pre><code>public class Foo{
    private Bar bar; //namespace something2
    private User user; //namespace user
  }
  </code></pre>
  
  <p>WHEN</p>
  
  <pre><code>JAXBContext c = JAXBContext.newInstance(Foo.class, Bar.class, User.class);
  ...
  Foo foo = new Foo();
  foo.setBar(null);
  foo.setUser(new User("Bob"));
  marshaller.umarshal(foo);
  </code></pre>
  
  <p>THEN I expect the xml to be</p>
  
  <pre><code>&lt;foo xmlns="something1"  xmlns:user="user"&gt;
    &lt;user:name&gt;Bob&lt;/user:name&gt;
  &lt;/foo&gt;
  </code></pre>
  
  <p>BUT the ACTUAL is <strong>(note the something2 namespace)</strong></p>
  
  <pre><code>&lt;foo xmlns="something1" xmlns:user="user" xmlns:bar="something2"&gt;
    &lt;user:name&gt;Bob&lt;/user:name&gt;
  &lt;/foo&gt;
  </code></pre>
  
  <p>Of course this is a simplified example and our specification of a type has around 30 different namespaces.</p>