Java - JAXB를 사용한 XML to Java Object

JAXB를 이용해서 XML 데이터를 자바 오브젝트로 변경할 수 있다.


*** Maven Depenendcy ***
<dependency>
    <groupId>javax.xml</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.1</version>
</dependency>

*** JAXB 사용예 ***

JAXBContext context = JAXBContext.newInstance(Cars.class);
Unmarshaller un = context.createUnmarshaller();

Cars cars = un.unmarshal(new File(a.xml)); // File, InputStream, URL 등 사용 가능


*** a.xml ***
<Cars>
    <CarList>
        <CarInfo>
            <Name>abc</Name>
            <Year>2001</Year>
        </CarInfo>
        <CarInfo>
            <Name>zzz</Name>
            <Year>1999</Year>
        </CarInfo>
    </CarList>
    <TotalCount>2</TotalCount>
</Cars>

*** Cars.java ***
@XmlRootElement(name = "Cars")
public class Cars
{
    private List<CarInfo> carList;
    private int totalCount;

    public List<CarInfo> getCarList() {
        return carList;
    }

    @XmlElementWrapper(name = "CarList") 
    @XmlElement(name = "CarInfo")
    public void setCarList(List<CarInfo> carList) {
        this.carList = carList;
    }

    public int getTotalCount() {
        return totalCount;
    }

    @XmlElement(name = "TotalCount")
    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }
}

*** CarInfo.java ***
@XmlRootElement(name = "CarInfo")
public class CarInfo
{
    private String name;
    private int year;

    public String getName() {
        return name;
    }

    @XmlElement(name = "Name")
    public void setName(String name) {
        this.name = name;
    }
  
    public int getYear() {
        return year;
    }

    @XmlElement(name = "Year")
    public void setYear(int year) {
        this.year = year;
    }
}