我有一个相当大的对象树,我想导出到XML。在几个地方使用名为Person的对象(作为userCreated,许多子实体的userModified,作为客户端等)
根据Person对象的使用,我需要在xml中使用不同的元素。例如:
<policy>
<userCreated>
<firstName>John</firstName>
<lastName>Doe</lastName>
</userCreated>
<client>
<clientId>1234</clientId>
<email>jdoe@example.com</email>
<firstName>John</firstName>
<lastName>Doe</lastName>
</client>
</policy>
userCreated和client是同一对象(名为Person)的实例
如何在bindings.xml中设置?
答案 0 :(得分:0)
您可以使用EclipseLink JAXB (MOXy)的@XmlNamedObjectGraph
扩展程序来支持此用例。 @XmlNamedObjectGraph
允许您执行的操作是为您的数据创建多个视图。
<强>人强>
下面我们将使用@XmlNamedObjectGraph
在Person
类上创建一个仅显示2个字段(firstName
和lastName
)的视图。
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.*;
@XmlNamedObjectGraph(
name = "simple",
attributeNodes = {
@XmlNamedAttributeNode("firstName"),
@XmlNamedAttributeNode("lastName")
}
)
@XmlAccessorType(XmlAccessType.FIELD)
public class Person {
private int clientId;
private String firstName;
private String lastName;
private String email;
public void setClientId(int clientId) {
this.clientId = clientId;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmail(String email) {
this.email = email;
}
}
<强>政策强>
我们还会在@XmlNamedObjectGraph
课程中使用Policy
。它表示对userCreated
字段应用我们在simple
类上定义的名为Person
的命名对象图。
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlNamedObjectGraph(
name = "policy",
attributeNodes = {
@XmlNamedAttributeNode(value = "userCreated", subgraph = "simple"),
@XmlNamedAttributeNode("client")
}
)
public class Policy {
private Person userCreated;
private Person client;
public void setUserCreated(Person userCreated) {
this.userCreated = userCreated;
}
public void setClient(Person client) {
this.client = client;
}
}
<强>演示强>
在下面的演示代码中,我们将使用Marshaller
属性指定要在MarshallerProperties.OBJECT_GRAPH
上应用的命名对象图。
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.MarshallerProperties;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Policy.class);
Person person = new Person();
person.setClientId(1234);
person.setFirstName("John");
person.setLastName("Doe");
person.setEmail("jdoe@example.com");
Policy policy = new Policy();
policy.setClient(person);
policy.setUserCreated(person);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.OBJECT_GRAPH, "policy");
marshaller.marshal(policy, System.out);
}
}
<强>输出强>
以下是运行演示代码的输出:
<?xml version="1.0" encoding="UTF-8"?>
<policy>
<userCreated>
<firstName>John</firstName>
<lastName>Doe</lastName>
</userCreated>
<client>
<clientId>1234</clientId>
<firstName>John</firstName>
<lastName>Doe</lastName>
<email>jdoe@example.com</email>
</client>
</policy>
了解更多信息