公司最近用WebService获取数据,数据格式是xml的,所以需要将xml转换成对象 下面是初步对XStream的一些学习使用!
程序需要两个jar包 分别是
运行Main类 有几个方法 根据方法名和注释你能很容易的找到你想要的
package com.xstream.demo;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class Demo {
public static void main(String[] args) throws Exception {
/*//对象转换成xml字符串
String xml = beanToXml();
//对象转换成xml文件
creatXMlFile(new File(“1.xml”));
//xml字符串转换成对象
xmlToBean(xml);*/
//xml文件转换成对象
// xmlToBean(new File(“1.xml”));
// List2Xml();
// creatXMlFile(new File(“2.xml”));
xmlToList(new File(“2.xml”));
}
/**
* 将xml字符串转换成对象
* @param xml
*/
public static void xmlToBean(String xml){
XStream xStream = new XStream(new DomDriver());
//注解生效
xStream.processAnnotations(new Class[]{Student.class});
//将xml字符串转换成对象
Student student = (Student)xStream.fromXML(xml);
System.out.println(student);
}
/**
* 将xml文件转换成对象
* @param xmlFile
*/
public static void xmlToBean(File xmlFile) {
XStream xStream=new XStream(new DomDriver());
xStream.processAnnotations(new Class[]{Student.class});
Student student = (Student)xStream.fromXML(xmlFile);
System.out.println(student);
}
/**
* 对象转换成xml字符串
* @return
*/
private static String beanToXml() {
//定义bean
Student student=new Student();
student.setName("张三");
student.setAge("18");
student.setSex("男");
List<StudentInfo> stuInfoList = new ArrayList<StudentInfo>();
stuInfoList.add(new StudentInfo("157","山西"));
stuInfoList.add(new StudentInfo("158","河南"));
student.setStuInfoList(stuInfoList);
//创建XStream对象
XStream stream=new XStream();
// 注册使用了注解的Student类
stream.processAnnotations(new Class[]{Student.class});
//转换为xml(默认格式化)
String xml=stream.toXML(student);
return xml;
}
/**
* 对象转换成xml文件
* @param file
* @throws IOException
*/
private static void creatXMlFile(File file) throws IOException {
String xml=List2Xml();
String xmlContent=”