- importjava.io.FileOutputStream;
- importjavax.xml.bind.JAXBContext;
- importjavax.xml.bind.Marshaller;
- importjavax.xml.bind.annotation.XmlRootElement;
- publicclassJavaToXMLDemo{
- staticvoidmain(String[]args)throwsException{
- JAXBContextcontext=JAXBContext.newInstance(Employee.class);
- Marshallerm=context.createMarshaller();
- m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
- Employeeobject=newEmployee();
- object.setCode("CA");
- object.setName("Cath");
- object.setSalary(300);
- m.marshal(object,System.out);
- }
- }
@XmlRootElement
classEmployee{
privateStringcode;
privateStringname;
privateintsalary;
publicStringgetCode(){
returncode;
voidsetCode(Stringcode){
this.code=code;
publicStringgetName(){
returnname;
voidsetName(Stringname){
this.name=name;
intgetSalary(){
returnsalary;
voidsetSalary(intpopulation){
this.salary=population;
运行结果:
- <?xmlversion="1.0"encoding="UTF-8"standalone="yes"?>
- <employee>
- code>CA</name>Cathsalary>300>