【问题标题】:MOXy JAXB: how to exclude elements from marshallingMOXy JAXB:如何从编组中排除元素
【发布时间】:2012-04-18 05:52:52
【问题描述】:

我有我的模型:

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

我这样填写对象:

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

这会产生下一个 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>

正如您所见,'id' 属性没有 @XmlPath 注释,但这也存在于最终的 XML 中。我知道我可以避免将 'id' 属性设置为 null 的这种行为,但我想知道是否有其他方法。关键是我的真实模型比这个大得多,我必须将很多属性设置为 null。

有什么帮助吗?

提前致谢。

【问题讨论】:

    标签: jaxb eclipselink moxy


    【解决方案1】:

    您可以使用@XmlTransient 标记属性以将其从 XML 表示中排除:

    @XmlTransient
    private Long id;
    

    或者您可以使用 @XmlAccessorType(XmlAccessType.NONE) 注释您的类型,以便仅映射带注释的字段/属性。

    @XmlAccessorType(XmlAccessType.NONE)
    public class CustomerTest {
    

    更多信息

    【讨论】:

    • 谢谢!你总是很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多