封送 POJO 属性与封送原始属性没有什么不同。引用的 POJO 类不需要用 进行批注。@XmlRootElement
Java 模型
员工
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Employee {
private Address address;
private int employeeId;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
}
地址
作为 的一部分进行编组,您不需要执行任何特殊操作。Address
Employee
public class Address {
private String street;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
演示代码
下面是一些演示代码,这些代码将填充和员工模型并将其封送为 XML。
演示
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Employee.class);
Address address = new Address();
address.setStreet("1 A Street");
Employee employee = new Employee();
employee.setEmployeeId(123);
employee.setAddress(address);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(employee, System.out);
}
}
输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
<address>
<street>1 A Street</street>
</address>
<employeeId>123</employeeId>
</employee>
重命名编组元素
如果要覆盖默认元素名称,则可以使用注释,而不管属性的类型如何。@XmlElement
员工
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Employee {
private Address address;
private int employeeId;
@XmlElement(name="ADDR")
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@XmlElement(name="ID")
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
}
输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
<ADDR>
<street>1 A Street</street>
</ADDR>
<ID>123</ID>
</employee>