2012-04-04 32 views
9

Tôi có mô hình của tôi:MOXY JAXB: làm thế nào để loại trừ các yếu tố từ marshalling

@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; 
} 

Và tôi điền vào các đối tượng như thế này:

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); 
     } 
    } 

này tạo ra XML tiếp theo:

<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> 

Như bạn có thể thấy không có chú giải @XmlPath cho thuộc tính 'id' nhưng điều này cũng có trong XML cuối cùng. Tôi biết tôi có thể tránh hành vi này thiết lập các 'id' tài sản để null nhưng tôi muốn biết nếu có một cách khác. Vấn đề là mô hình thực sự của tôi lớn hơn nhiều so với mô hình này và tôi sẽ phải đặt rất nhiều thuộc tính thành null.

Bất kỳ trợ giúp nào?

Xin cảm ơn trước.

Trả lời

15

Bạn có thể đánh dấu các tài sản với @XmlTransient để có nó loại trừ khỏi các đại diện XML:

@XmlTransient 
private Long id; 

Hoặc bạn có thể chú thích kiểu của bạn với @XmlAccessorType(XmlAccessType.NONE) lĩnh vực để chỉ chú thích/tài sản được ánh xạ.

@XmlAccessorType(XmlAccessType.NONE) 
public class CustomerTest { 

Để biết thêm thông tin

+1

Cảm ơn bạn! Bạn luôn rất hữu ích. – rocotocloc

Các vấn đề liên quan