测试所有的jar包:
1. spring-oxm.jar
2. xmlpull.jar
3. xpp3.jar
4. xstream.jar
一. 上下文配置:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注解扫描 --> <context:component-scan base-package="cn.com.springwalker"/> <!-- 封装spring 的 xstreamMarshaller --> <bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"> <property name="autodetectAnnotations" value="true"/> </bean> </beans>
二 .测试类:
package cn.com.springwalker.test.oxm.xstream.converter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
/**
* @author: lihaoquan
*/
public class PersonTest {
public static void main(String[] args) throws Exception {
String chartset = "UTF-8";
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Marshaller marshaller = (Marshaller) context.getBean("xstreamMarshaller");
Unmarshaller unmarshaller = (Unmarshaller) context.getBean("xstreamMarshaller");
/**
* 创建输出流
*/
ByteArrayOutputStream os = new ByteArrayOutputStream();
ByteArrayInputStream is = null;
try {
Person person = new Person();
person.setName("张三");
String xml = "";
/**
* 对象转化为XML
*/
if(marshaller!=null) {
marshaller.marshal(person,new StreamResult(os));
xml = os.toString(chartset);//设置字符编码
}
System.out.println(xml);
/**
* XML转化为对象
*/
byte[] bytes = xml.getBytes(chartset);//设置字符编码
is = new ByteArrayInputStream(bytes);
Person newPerson = (Person) unmarshaller.unmarshal(new StreamSource(is));
if(newPerson!=null) {
System.out.println("获取姓名::"+newPerson.getName());
}
}catch (Exception e) {
e.printStackTrace();
}finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
}
}
}