编辑这个页面须要登录或更高权限!
Xstream 是一个库,用于将对象序列化为xml,反之亦然,而无需任何映射文件。注意,castor需要一个映射文件。
XStreamMarshaller 类提供了将对象编组为xml的功能,反之亦然。
您需要为创建以下文件通过Xstream使用Spring将Java对象编组为XML:
Employee.java applicationContext.xml Client.java
要运行此示例,您需要加载:
Spring Core jar文件 Spring Web jar文件 xstream-1.3.jar
下载spring的所有jar文件,包括core,web,aop,mvc,j2ee,remoting ,oxm,jdbc,orm等。
下载xstream-1.3.jar
Employee.java
如果定义了三个属性id,setter和getters的名称和薪金。
package com.nhooo; 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
它定义了一个Bean xstreamMarshallerBean,其中Employee类与OXM框架绑定。
<?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.nhooo.Employee"></property> </bean> </beans>
Client.java
它从applicationContext.xml文件获取Marshaller的实例并调用marshal方法。
package com.nhooo; 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 Sucessfully"); } }
employee.xml
<com.nhooo.Employee> <id>101</id> <name>Sonoo Jaiswal</name> <salary>100000.0</salary> </com.nhooo.Employee>