如何使用@XmlElement和@XmlRootElement对对象内部的对象进行编组?

2022-09-02 12:16:55

我见过许多JAXB的实现,我们可以使用注释将java原语转换为XML元素。@XmlElement

但是,我想将以下POJO转换为XML(请注意,员工类中有一个地址对象,而不仅仅是基元):

public class Employee {
    private Address address;
    private int employeeId;

    // constructors + setters + getters
}

如何使用这些 JAXB 注释将员工对象编组到 XML?

谢谢。


答案 1

封送 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;
    }

}

地址

作为 的一部分进行编组,您不需要执行任何特殊操作。AddressEmployee

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>

答案 2

我能够通过以下给出的 appraoch(即通过用注释对两个类进行注释)来实现 JAXB 的“对象内对象”XML 编组:@XmlRootElement

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Employee {
    @XmlElement
    private Address address;
     .
     .
}

@XmlRootElement
public class Address {
    .
    .
}

推荐