Switch to full style
JAXB code examples
Post a reply

Marshal Java object to xml

Tue Jul 07, 2009 11:17 pm

Marshal Java object to xml :

In the following example , we marshal the java object to XML and print it in to console on it .

Code:
import java.io.FileOutputStream;

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


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

    Marshaller marshallerObj = contextObj.createMarshaller();
    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Student myStudent = new Student();
    myStudent.setGender("M");
    myStudent.setName("Amar");
    myStudent.setAge(20);

    marshallerObj .marshal(myStudent, System.out);

  }
}


Code:
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
class Student{
  private String gender;

  private String name;

  private int age;

  public String getGender() {
    return gender;
  }

  public void setGender(String gender) {
    this.gender= gender;
  }

  public String getName() {
    return name;
  }

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

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age= age;
  }
}


Output XML file example :

Code:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student>
    <gender>M</gender>
    <name>Amar</name>
    <age>20</age>
</student>




Post a reply
  Related Posts  to : Marshal Java object to xml
 Marshal Java object to XML file     -  
 object's finalize() in java     -  
 Java Object Reading     -  
 Object without new Operator     -  
 use out object in a method at jsp     -  
 object detection     -  
 Connection object in jsp     -  
 Object Orientation in c++, how to a do object Orientation     -  
 3D-object loader     -  
 How to use connection object in jsp     -  

Topic Tags

Java XML, Java JAXB