如何使用JAXB创建POJO的XML文件?

下面的代码段显示了如何使用JAXB将POJO转换为XML文件。为此,我们可以将要保存XML的输出文件传递到该marshaller对象。

package org.nhooo.example.jaxb;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.File;

public class JAXBObjectToXmlFile {
    public static void main(String[] args) {
        Track track = new Track();
        track.setId(2);
        track.setTitle("She Loves You");

        try {
            JAXBContext context = JAXBContext.newInstance(Track.class);

            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            File output = new File("Track.xml");            
            marshaller.marshal(track, output);
        } catch (JAXBException e) {            
            e.printStackTrace();
        }
    }
}

此代码片段将创建一个文件Track.xml,其内容如下:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<track id="2">
    <title>She Loves You</title>
</track>