Spring OXM - Test Project for XStream



Update the OxmApplication.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.

XStream restricts the unmarshelling of object by default. We're giving all permission using following line −

//add permission
unmarshaller.getXStream().addPermission(AnyTypePermission.ANY);

OxmApplication.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.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.XmlMappingException;
import org.springframework.oxm.xstream.XStreamMarshaller;

import com.thoughtworks.xstream.security.AnyTypePermission;
import com.tutorialspoint.oxm.model.Student;

public class OxmApplication {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");  
      XStreamMarshaller marshaller = (XStreamMarshaller)context.getBean("xstreamMarshaller");
      XStreamMarshaller unmarshaller = (XStreamMarshaller)context.getBean("xstreamMarshaller");

      //add permission
      unmarshaller.getXStream().addPermission(AnyTypePermission.ANY);
      // 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

Now in eclipse, right click on the MainApp.java, select Run As context menu, and select Java Application. Check the console logs in the eclipse. You can see the below logs −

Student marshalled successfully.
Age: 14, Name: Soniya
Advertisements