Total members 11890 |It is currently Fri Apr 19, 2024 6:27 pm Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





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>




_________________
M. S. Rakha, Ph.D.
Queen's University
Canada


Author:
Mastermind
User avatar Posts: 2715
Have thanks: 74 time
Post new topic Reply to topic  [ 1 post ] 

  Related Posts  to : Marshal Java object to xml
 Marshal Java object to XML file     -  
 object's finalize() in java     -  
 Java Object Reading     -  
 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     -  
 Object without new Operator     -  
 use out object in a method at jsp     -  



Topic Tags

Java JAXB, Java XML






Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com