如何使用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>
热门推荐
6 足球队祝福语简短
10 端午发给客户祝福语简短
11 祖国生日祝福语简短英文
12 宝宝生日祝福语大全简短
13 怎么说祝福语简短
14 情人表白祝福语简短大气
15 婶婶生日贺词简短祝福语
16 孩子16岁祝福语简短
17 初八祝福语简短语
18 写给情侣祝福语 浪漫简短