2016-10-31 77 views
0

讓我們假設我有以下XML:如何使用JAXB將元素上的屬性映射到POJO的內部屬性的字段?

<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 

回答

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; 
    } 
} 
相關問題