Switch to full style
JAXB code examples
Post a reply

Marshal Java object to XML file

Tue Jul 07, 2009 11:47 pm

Marshal Java object to xml file :

In the following example , we marshal the java object to XML and write it in a file .

java 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(object, new FileOutputStream("Student.xml"));  
 

  }


java 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 :

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




Re: Marshal Java object to XML file

Fri Jul 10, 2009 9:19 am

Today I had a little problem with component mapping and the attributes. And It has something to do with the fact that all my objects use interfaces.

Re: Marshal Java object to XML file

Sun Jul 12, 2009 8:08 am

how ?

Post a reply
  Related Posts  to : Marshal Java object to XML file
 Marshal Java object to xml     -  
 Object File Directives Usage PIC Assembly     -  
 Read file content to StringBuffer String object     -  
 Copy file to file in java code- implementation     -  
 Java Object Reading     -  
 object's finalize() in java     -  
 Encrypt/Decrypt a file from source file to target file.     -  
 Creating a JAR file in Java     -  
 Java File age monitoring     -  
 get the Contents of a ZIP File in java     -  

Topic Tags

Java JAXB, Java XML