English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Xstream It is a library used to serialize objects to xml and vice versa without any mapping file. Note that castor requires a mapping file.
XStreamMarshaller The class provides the functionality to marshal objects to xml and vice versa.
You need to use Xstream to create the following files through Spring for Java object marshalling to XML:
Employee.java applicationContext.xml Client.java
To run this example, you need to load:
Spring Core jar file Spring Web jar file xstream-1.3.jar
Download all jar files of spring, including core, web, aop, mvc, j2ee, remoting, oxm, jdbc, orm, etc.
Download xstream-1.3.jar
Employee.java
If three properties id, setter and getters of salary are defined.
package com.w3codebox; public class Employee { private int id; private String name; private float salary; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getSalary() { return salary; } public void setSalary(float salary) { this.salary = salary; } }
applicationContext.xml
It defines a Bean named xstreamMarshallerBean, where the Employee class is bound to the OXM framework.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="xstreamMarshallerBean" class="org.springframework.oxm.xstream.XStreamMarshaller"> <property name="annotatedClasses" value="com.w3codebox.Employee"></property> </bean> </beans>
Client.java
It retrieves an instance of Marshaller from the applicationContext.xml file and calls the marshal method.
package com.w3codebox; import java.io.FileWriter; import java.io.IOException; import javax.xml.transform.stream.StreamResult; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.oxm.Marshaller; public class Client{ public static void main(String[] args) throws IOException{ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Marshaller marshaller = (Marshaller)context.getBean("xstreamMarshallerBean"); Employee employee = new Employee(); employee.setId(101); employee.setName("Sonoo Jaiswal"); employee.setSalary(100000); marshaller.marshal(employee, new StreamResult(new FileWriter("employee.xml"))); System.out.println("XML Created Successfully"); } }
employee.xml
<com.w3codebox.Employee> <id>101</id> <name>Sonoo Jaiswal</name> <salary>100000.0</salary> </com.w3codebox.Employee>