用JAXB从对象生成XML

前端之家收集整理的这篇文章主要介绍了用JAXB从对象生成XML前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Java代码
  1. importjava.io.FileOutputStream;
  2. importjavax.xml.bind.JAXBContext;
  3. importjavax.xml.bind.Marshaller;
  4. importjavax.xml.bind.annotation.XmlRootElement;
  5. publicclassJavaToXMLDemo{
  6. staticvoidmain(String[]args)throwsException{
  7. JAXBContextcontext=JAXBContext.newInstance(Employee.class);
  8. Marshallerm=context.createMarshaller();
  9. m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
  10. Employeeobject=newEmployee();
  11. object.setCode("CA");
  12. object.setName("Cath");
  13. object.setSalary(300);
  14. m.marshal(object,System.out);
  15. }
  16. }

@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;
  • 运行结果:

    Xml代码
      <?xmlversion="1.0"encoding="UTF-8"standalone="yes"?>
    1. <employee>
    2. code>CA</name>Cathsalary>300>
    原文链接:https://www.f2er.com/xml/299966.html
  • 猜你在找的XML相关文章