jaxb

来源:互联网 发布:淘宝店铺宣传广告语 编辑:程序博客网 时间:2024/06/06 20:59

首先导入:javax.xml.bind

package com.xml;


import javax.xml.bind.annotation.XmlAttribute;  
import javax.xml.bind.annotation.XmlElement;  
import javax.xml.bind.annotation.XmlRootElement;  


@XmlRootElement 
public class Customer {
String name;  
    int age;  
    int id;
    
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
@XmlAttribute 
public void setId(int id) {
this.id = id;
}  
    
}


package com.xml;


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


public class JAXBExample {
public static void main(String[] args) {  
   Customer customer = new Customer();  
   customer.setId(100);  
   customer.setName("mkyong");  
   customer.setAge(29);  
  
   try {  
  
     File file = new File("f:\\file.xml");  
     JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);  
     Marshaller jaxbMarshaller = jaxbContext.createMarshaller();  
  
     // output pretty printed  
     jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  
 
     jaxbMarshaller.marshal(customer, file);  
     jaxbMarshaller.marshal(customer, System.out);  
  
     } catch (JAXBException e) {  
     e.printStackTrace();  
  }  
  
}  
}













0 0
原创粉丝点击