JAXB

01package com.mkyong.core;
02  
03import javax.xml.bind.annotation.XmlAttribute;
04import javax.xml.bind.annotation.XmlElement;
05import javax.xml.bind.annotation.XmlRootElement;
06  
07@XmlRootElement
08public class Customer {
09  
10    String name;
11    int age;
12    int id;
13  
14    public String getName() {
15        return name;
16    }
17  
18    @XmlElement
19    public void setName(String name) {
20        this.name = name;
21    }
22  
23    public int getAge() {
24        return age;
25    }
26  
27    @XmlElement
28    public void setAge(int age) {
29        this.age = age;
30    }
31  
32    public int getId() {
33        return id;
34    }
35  
36    @XmlAttribute
37    public void setId(int id) {
38        this.id = id;
39    }
40  
41}

[代码] JAXBExample.java

01package com.mkyong.core;
02  
03import java.io.File;
04import javax.xml.bind.JAXBContext;
05import javax.xml.bind.JAXBException;
06import javax.xml.bind.Marshaller;
07  
08public class JAXBExample {
09    public static void main(String[] args) {
10  
11      Customer customer = new Customer();
12      customer.setId(100);
13      customer.setName("mkyong");
14      customer.setAge(29);
15  
16      try {
17  
18        File file = new File("C:\\file.xml");
19        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
20        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
21  
22        // output pretty printed
23        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
24  
25        jaxbMarshaller.marshal(customer, file);
26        jaxbMarshaller.marshal(customer, System.out);
27  
28          } catch (JAXBException e) {
29        e.printStackTrace();
30          }
31  
32    }
33}

[代码] 输出

1<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2<customer id="100">
3    <age>29</age>
4    <name>mkyong</name>
5</customer>

[代码] 将XML转为对象

01package com.mkyong.core;
02  
03import java.io.File;
04import javax.xml.bind.JAXBContext;
05import javax.xml.bind.JAXBException;
06import javax.xml.bind.Unmarshaller;
07  
08public class JAXBExample {
09    public static void main(String[] args) {
10  
11     try {
12  
13        File file = new File("C:\\file.xml");
14        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
15  
16        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
17        Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
18        System.out.println(customer);
19  
20      } catch (JAXBException e) {
21        e.printStackTrace();
22      }
23  
24    }
25}

[代码] 输出

1Customer [name=mkyong, age=29, id=100]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值