编组和解组可以表现不同吗?

时间:2014-12-02 08:14:09

标签: jaxb marshalling unmarshalling

以此对象为例:

public class Person {

    @XmlAttribute
    private String name = null;

    @XmlElement
    private Address address = null;

    // getters and setters
}

XML文件:

<person name="blabla">
    <address>...</address>
</person>

如果我想在umarshalling时加载一个完整的Person对象(名称+地址)但在编组时只保存其名称,我该怎么办? (即不保存地址)

1 个答案:

答案 0 :(得分:0)

最简单的方法是制作copy并删除不必要的数据。

另一个(更复杂的选项)选项是定义不同的映射。这是possible with MOXy

Map<String, Object> tenantOneProps = new HashMap<String, Object>();
ArrayList tenantOneBindings = new ArrayList();
tenantOneBindings.add("examples/virtual/base-bindings.xml");
tenantOneBindings.add("examples/virtual/binding-tenant1.xml");
tenantOneProps.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, tenantOneBindings);
JAXBContext tentantOneContext = JAXBContext.newInstance(new Class[] {Customer.class, Address.class}, tenantOneProps);

Map<String, Object> tenantTwoProps= new HashMap<String, Object>();
ArrayList tenantTwoBindings = new ArrayList();
tenantTwoBindings.add("examples/virtual/base-bindings.xml");
tenantTwoBindings.add("examples/virtual/binding-tenant2.xml");
tenantTwoProps.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, tenantTwoBindings);
JAXBContext tentantTwoContext = JAXBContext.newInstance(new Class[] {Customer.class, Address.class}, tenantTwoProps);

在此定义两组映射 - base加上tenant1tenant2。因此,您创建了两个上下文。你可以用一个解组,然后用另一个编组。