English 中文(简体)
Spring OXM - Test JAXB2
  • 时间:2024-11-05

Spring OXM - Test JAXB2


Previous Page Next Page  

Create a main class OXMApppcation.java with marshaller and unmarshaller objects. The objective of this class is to marshall a student object to student.xml using marshaller object and then unmarshall the student.xml to student object using unmarshaller object.

Example

OXMApppcation.java


package com.tutorialspoint.oxm;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException;
import com.tutorialspoint.oxm.model.Student;

pubpc class OXMApppcation {
   pubpc static void main(String[] args) {
      ApppcationContext context = new ClassPathXmlApppcationContext("apppcationcontext.xml");  
      Marshaller marshaller = (Marshaller)context.getBean("jaxbMarshaller");
      Unmarshaller unmarshaller = (Unmarshaller)context.getBean("jaxbMarshaller");

      // create student object
      Student student = new Student();
      student.setAge(14);
      student.setName("Soniya");

      try {
         marshaller.marshal(student, new StreamResult(new FileWriter("student.xml")));  
         System.out.println("Student marshalled successfully.");  
         FileInputStream is =  new FileInputStream("student.xml");
         Student student1 = (Student)unmarshaller.unmarshal(new StreamSource(is));
         System.out.println("Age: " + student1.getAge() + ", Name: " + student1.getName());
      } catch(IOException | XmlMappingException ex) {
         ex.printStackTrace();
      }
   }
}

Output

Right cpck in the content area of the file in ecppse and then select Run as java apppcation and verify the output.


Oct 10, 2021 8:48:12 PM org.springframework.context.support.ClassPathXmlApppcationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApppcationContext@1e127982: startup date 
[Sun Oct 10 20:48:12 IST 2021]; root of context hierarchy
Oct 10, 2021 8:48:12 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [apppcationcontext.xml]
Oct 10, 2021 8:48:13 PM org.springframework.oxm.jaxb.Jaxb2Marshaller createJaxbContextFromClasses
INFO: Creating JAXBContext with classes to be bound [class com.tutorialspoint.oxm.model.Student]
Student marshalled successfully.
Age: 14, Name: Soniya
Advertisements