如何使用JAVA创建XML文件

时间:2016-04-22 05:23:17

标签: java

我想以这种格式创建一个XML文件:

<msgs>
    <msg>
        <type>sense</type>
        <cid>168</cid>
        <ip>192.168.140.150</ip>
        <errs/>
        <id>002EC0FEFF83EA97</id>
        <sensors>
            <sensor sid='002EC0FEFF8FFF27' desc='' batt='6.60' sig='-55' scount='0' rdate='15/05/2015 21:47:04' mdate='18/04/2016 08:06:25' />
            <sensor sid='002EC0FEFF8FFF27' desc='' batt='6.60' sig='-55' scount='0' rdate='15/05/2015 21:47:04' mdate='18/04/2016 08:07:25' />
            <sensor sid='002EC0FEFF8FFF27' desc='' batt='6.60' sig='-55' scount='0' rdate='15/05/2015 21:47:04' mdate='18/04/2016 08:08:25' />
        </sensors>
    </msg>
</msgs>

创建XML后,我想将此文件保存在文件夹

1 个答案:

答案 0 :(得分:0)

使用“JAXB”可以将java对象转换为xml,然后将其写入文件。

将值设置为Student对象并将put打印到控制台的示例代码

JAXBContext context = JAXBContext.newInstance(Student.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

Student object = new Student();
object.setId(11);
object.setName("Bob");
m.marshal(object, System.out);