用JAXB从对象生成XML

Java代码   收藏代码
  1. import java.io.FileOutputStream;  
  2.   
  3. import javax.xml.bind.JAXBContext;  
  4. import javax.xml.bind.Marshaller;  
  5. import javax.xml.bind.annotation.XmlRootElement;  
  6.   
  7. public class JavaToXMLDemo {  
  8.   public static void main(String[] args) throws Exception {  
  9.     JAXBContext context = JAXBContext.newInstance(Employee.class);  
  10.   
  11.     Marshaller m = context.createMarshaller();  
  12.     m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  
  13.   
  14.     Employee object = new Employee();  
  15.     object.setCode("CA");  
  16.     object.setName("Cath");  
  17.     object.setSalary(300);  
  18.   
  19.     m.marshal(object, System.out);  
  20.   
  21.   }  
  22. }  

 

 

Java代码   收藏代码
  1. @XmlRootElement  
  2. class Employee {  
  3.   private String code;  
  4.   
  5.   private String name;  
  6.   
  7.   private int salary;  
  8.   
  9.   public String getCode() {  
  10.     return code;  
  11.   }  
  12.   
  13.   public void setCode(String code) {  
  14.     this.code = code;  
  15.   }  
  16.   
  17.   public String getName() {  
  18.     return name;  
  19.   }  
  20.   
  21.   public void setName(String name) {  
  22.     this.name = name;  
  23.   }  
  24.   
  25.   public int getSalary() {  
  26.     return salary;  
  27.   }  
  28.   
  29.   public void setSalary(int population) {  
  30.     this.salary = population;  
  31.   }  
  32. }  

 

 

运行结果:

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>  
  2. <employee>  
  3.     <code>CA</code>  
  4.     <name>Cath</name>  
  5.     <salary>300</salary>  
  6. </employee>  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值