用JAXB从对象生成XML

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

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;

public class JavaToXMLDemo {
  public static void main(String[] args) throws Exception {
    JAXBContext context = JAXBContext.newInstance(Employee.class);

    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Employee object = new Employee();
    object.setCode("CA");
    object.setName("Cath");
    object.setSalary(300);

    m.marshal(object, System.out);

  }
}

 

 

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

  private String name;

  private int salary;

  public String getCode() {
    return code;
  }

  public void setCode(String code) {
    this.code = code;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getSalary() {
    return salary;
  }

  public void setSalary(int population) {
    this.salary = population;
  }
}

 

 

运行结果:

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>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
    <code>CA</code>
    <name>Cath</name>
    <salary>300</salary>
</employee>

 

你可能感兴趣的:(JAXB)