MOXy JAXB: how to exclude elements from marshalling

rocotocloc picture rocotocloc · Apr 4, 2012 · Viewed 8.7k times · Source

I have my model:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class CustomerTest {

    private Long id;

    @XmlPath("contact-info/billing-address")
    private AddressTest billingAddress;

    @XmlPath("contact-info/shipping-address") 
    private AddressTest shippingAddress;

    @XmlPath("FileHeader/SchemaVersion/text()")
    private String schemaVersion;
}

And I fill in the object like this:

private void marshallCustomerTest() {
        try {
            JAXBContext jc = JAXBContext.newInstance(CustomerTest.class);

            CustomerTest customer = new CustomerTest();
            customer.setId(new Long(10));
            customer.setSchemaVersion("3.2");

            AddressTest billingAddress = new AddressTest();
            billingAddress.setStreet("1 Billing Street");
            customer.setBillingAddress(billingAddress);

            AddressTest shippingAddress = new AddressTest();
            shippingAddress.setStreet("2 Shipping Road");
            customer.setShippingAddress(shippingAddress);

            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            m.marshal(customer, System.out);
        } catch (JAXBException jex) {
            jex.printStackTrace();
            log.error(jex);
        }
    }

This produce the next XML:

<customerTest xmlns:fe="http://www.facturae.es/Facturae/2009/v3.2/Facturae" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
   <id>10</id>
   <contact-info>
      <billing-address>
         <street>1 Billing Street</street>
      </billing-address>
      <shipping-address>
         <street>2 Shipping Road</street>
      </shipping-address>
   </contact-info>
   <FileHeader>
      <SchemaVersion>3.2</SchemaVersion>
   </FileHeader>
</customerTest>

As you can see there is not @XmlPath annotation for 'id' property but this is also present in the final XML. I know I can avoid this behaviour setting the 'id' property to null but I want to know if there is another way. The point is that my real model is much bigger than this one and I would have to set a lot of properties to null.

Any help?

Thanks in advance.

Answer

bdoughan picture bdoughan · Apr 4, 2012

You can either mark the property with @XmlTransient to have it excluded from the XML representation:

@XmlTransient
private Long id;

Or you can annotate your type with @XmlAccessorType(XmlAccessType.NONE) so that only annotated fields/properties are mapped.

@XmlAccessorType(XmlAccessType.NONE)
public class CustomerTest {

For More Information