public static void main(String[] args) throws FileNotFoundException {
Customer customer = new Customer();
customer.setId(100);
customer.setName("suo");
// customer.setAge(29);
try {
File file = new File("C:\\file3.xml");
OutputStream os = new FileOutputStream(file);
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);
jaxbMarshaller.marshal(customer,os);
} catch (JAXBException e){
e.printStackTrace();
}
}
}
//---------------------
//Unmarshaller
public class Xml2ObjectDemo {
public static void main(String[] args) {
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
//-------------
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;
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Customer [id=" + id + ",name=" + name + ",age=" + age + "]";
}
}