如何使用JAXB将元素上的属性映射到POJO的内部属性的字段?

时间:2016-10-31 05:10:46

标签: java xml jaxb

让我假装我有以下XML:

<company name="Sun" country="Atlantis" state="Syracuse" city="Troy">
</company>

使用JAXB,并且不使用诸如EclipseLink @XmlPath之类的第三方扩展,有没有办法将其解组为以下POJO结构:

@XmlRootElement
public class Company {

    private String name;

    private Address address;

    // getters and setters

}

public class Address {

    private String country;

    private String state;

    private String city;

    // getters and setters

}

company.getAddress().getCountry(); // Atlantis

1 个答案:

答案 0 :(得分:0)

可以使用XmlAdapter

处理此特定方案
import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.time.format.DateTimeFormatter;

public class CompanyAdapter extends XmlAdapter<CompantType, Company> {

    @Override
    public CompanyType marshal(Company in) throws Exception {
        CompanyType out = new CompanyType();

        out.setName(in.getName());
        out.setCountry(in.getAddress().getCountry());
        // ...

        return out;
    }

    @Override
    public Company unmarshall(CompanyType in) throws Exception {
        Company out = new Company();

        out.setName(in.getName());

        Address add = new Address();
        add.setCountry(in.getCountry());

        out.setAddress(add);

        // ...

        return out;
    }
}